-
特性
- 一种文档数据库(BSON documents)
- 高性能、丰富的查询语言、高可用、横向扩展、支持多存储引擎
-
Shell(js接口)
- Date:
- Date(),返回当前时间的String
- new Date(),返回Date,通过ISODate()的包装器
- ISODate(),ISODate("2012-12-19T06:01:17.171Z")
- 检查类型:mydoc._id instanceof ObjectId
- show dbs,use <db>,show users
-
gte(大于等于)、
lte
- Date:
-
CRUD操作
- 插入
- collection 不存在会自动创建
- 插入无_id字段时会自动创建
- db.collection.insertOne() :db. users. insertOne({name: "sue",age: 26,status: "pending"}
- db.collection.insertMany() :
- 查找:db.collection.find()
- db.inventory.find( { status: "D" } )
- 嵌入文档查询条件:db.inventory.find( { "size.uom": "in" } )
- 数组
- db.inventory.find( { tags: ["red", "blank"] } ),包含
- db.inventory.find( { tags: { $all: ["red", "blank"] } } ),都包含且没有其他的元素
- 返回值:db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } ),等同于SELECT item, status from inventory WHERE status = "A"
- sort、skip、limit、comunt
db.inventory.find( { status: { $in: [ "A", "D" ] } } ) db.inventory.find( { status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] } ) db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
- 更新
- db.collection.updateOne()
- db.collection.updateMany()
- db.collection.replaceOne()
- 其他能起到更新效果的方法:
- db.collection.findOneAndReplace().
- db.collection.findOneAndUpdate().
- db.collection.findAndModify().
- db.collection.save().
- db.collection.bulkWrite().
- 删除
- db.collection.deleteOne()
- db.collection.deleteMany()
- 其他方法:
- db.collection.findOneAndDelete().
- db.collection.findAndModify().
- db.collection.bulkWrite().
db.inventory.insertMany([ { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }, { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } } ])
SQL Terms/Concepts MongoDB Terms/Concepts database database table collection row document or BSON document column field index index table joins $lookup, embedded documents primary key(Specify any unique column or column combination as primary key.) primary key (In MongoDB, the primary key is automatically set to the _id field.) aggregation (e.g. group by) aggregation pipeline transactions transactions -
文本搜索
- 文本索引:db.stores.createIndex( { name: "text", description: "text" } )
- 搜索:db.stores.find( {
search: "java coffee shop" } } )
- 聚合管道的文本搜索
db.articles.aggregate( [ { $match: { $text: { $search: "cake" } } }, { $group: { _id: null, views: { $sum: "$views" } } } ] )
-
地理位置(GEO)
- GeoJSON Point
location: { type: "Point", coordinates: [-73.856077, 40.848447] }
- 插入
-
聚合(Aggregation,这个可以点进去看一下)
-
管道聚合(Aggregation Pipeline)
- db.aggregate( [ { <stage> }, ... ] )
- Operator Expressions
- Arithmetic Expression Operators:
add,
mod,$power……
- Array Expression Operators:
range,$size……
- Boolean Expression Operators:
not,$or
- Comparison Expression Operators:
eq(equal),
gte,
lte,$ne(not equal)
- Conditional Expression Operators
- Date Expression Operators
- Arithmetic Expression Operators:
- 比较
SQL Terms, Functions, and Concepts MongoDB Aggregation Operators WHERE $match GROUP BY $group HAVING $match SELECT $project ORDER BY $sort LIMIT $limit SUM() $sum COUNT() sortByCount
join $lookup - 示例
-
{//orders
cust_id: "abc123",
ord_date: ISODate("2012-11-02T17:04:11.102Z"),
status: 'A',
price: 50,
items: [ { sku: "xxx", qty: 25, price: 1 },
{ sku: "yyy", qty: 25, price: 1 } ]
}
SELECT COUNT(*) AS count FROM orders
db.orders.aggregate( [
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
] )
SELECT cust_id,
SUM(price) as total
FROM orders
WHERE status = 'A'
GROUP BY cust_id
db.orders.aggregate( [
{ $match: { status: 'A' } },
{
$group: {
_id: "$cust_id",
total: { $sum: "$price" }
}
},
{ $match: { total: { $gt: 250 } } }
] )
- map-reduce
//案例:计算每个单位订单中数量的平均值(Calculate Order and Total Quantity with Average Quantity Per Item)
{// collection orders
_id: ObjectId("50a8240b927d5d8b5891743c"),
cust_id: "abc123",
ord_date: new Date("Oct 04, 2012"),
status: 'A',
price: 25,
items: [ { sku: "mmm", qty: 5, price: 2.5 },
{ sku: "nnn", qty: 5, price: 2.5 } ]
}
//提交(key,value),对每个items数组提取sku作为key,qty作为value数组的一个字段,count初始化为1
var mapFunction2 = function() {
for (var idx = 0; idx < this.items.length; idx++) {
var key = this.items[idx].sku;
var value = {
count: 1,
qty: this.items[idx].qty
};
emit(key, value);
}
};
// 对每个key,合并value
var reduceFunction2 = function(keySKU, countObjVals) {
reducedVal = { count: 0, qty: 0 };
for (var idx = 0; idx < countObjVals.length; idx++) {
reducedVal.count += countObjVals[idx].count;
reducedVal.qty += countObjVals[idx].qty;
}
return reducedVal;
};
// 对每个key,计算订单中数量的平均值
var finalizeFunction2 = function (key, reducedVal) {
reducedVal.avg = reducedVal.qty/reducedVal.count;
return reducedVal;
};
// query 条件
db.orders.mapReduce( mapFunction2,
reduceFunction2,
{
out: { merge: "map_reduce_example" },
query: { ord_date:
{ $gt: new Date('01/01/2012') }
},
finalize: finalizeFunction2
}
)