mongo命令之二

mongo中的操作符

以 $ 開頭

$set # 更新字段
$unset # 刪除字段
KaTeX parse error: Expected 'EOF', got '#' at position 6: inc #̲ 自增 {inc: {money: 10}} | 自減 {$inc: {money: -10}}
$exists # 是否存在
$in # 是否在…範圍
$and
$or
$push # 向數組中尾部添加一個元素
$addToSet # 向集合中添加元素
$pop # 刪除數組中的頭部或尾部元素

插入數據之insert

var user = {“name”: “mengdee”, “age”: 20, “address”: “上海市浦東新區張江鎮”, “create_time”: new Date()}
db.users.insert(user)
WriteResult({ “nInserted” : 1 })

db.users.insertOne({“username”: “mengday3”})
{
“acknowledged” : true,
“insertedId” : ObjectId(“5976b632670af2aa52ea90e1”)
}

db.users.insertMany([{“username”: “mengday4”}, {“username”: “mengday5”}])
{
“acknowledged” : true,
“insertedIds” : [
ObjectId(“5976b666670af2aa52ea90e2”),
ObjectId(“5976b666670af2aa52ea90e3”)
]
}

// 不指定id 自動生成objID, 也可以指定插入

db.users.insert({"_id":1,“name”:“nick”})

// 注意insert 在插入的時候如果已經存在了相同的id會報錯
// 如果想要存在相同的id的時候不報錯而是更新數據 請使用 save方法

插入數據之save
// 如果插入的時候數據不存在,就是插入
// 如果數據已存在,就會替換數據,注意是替換,不是更新,更新API是可以更新指定字段的,save不行

db.users.find()
{ “_id” : 1, “username” : “mengday8” }
{ “_id” : 2, “username” : “mengday8” }
db.users.save({ “_id” : 3, “mengday9” : 20})
WriteResult({ “nMatched” : 0, “nUpserted” : 1, “nModified” : 0, “_id” : 3 })
db.users.save({ “_id” : 2, “age” : 20, “gender”: 1 })
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday8” }
{ “_id” : 2, “age” : 20, “gender” : 1 }
{ “_id” : 3, “mengday9” : 20 }

db.users.save([{ “_id” : 4, “username”: “mengday9”}, { “_id” : 5, “username”:“mengday10”}])

更新數據之update
// 語法:
db.collection.update(
,
,
{
upsert: ,
multi: ,
writeConcern: ,
collation: ,
arrayFilters: [ , … ]
}
)
// addOrUpdate可選,爲true,就是查詢的數據不存在時,就將更新的數據作爲新數據插入.否則不插入
// multi可選。如果設置爲true,則更新符合query 條件的多個文檔。如果設置爲false,則更新一個文檔。默認值爲false
// 示例1 例如,給定一個books包含以下文檔的集合:
{
_id: 1,
item: “TBD”,
stock: 0,
info: { publisher: “1111”, pages: 430 },
tags: [ “technology”, “computer” ],
ratings: [ { by: “ijk”, rating: 4 }, { by: “lmn”, rating: 5 } ],
reorder: false
}
//更新部分字段
db.books.update(
{ _id: 1 },
{
$inc: { stock: 5 }, # 自增或者自減,整數爲負值 就是自減
$set: { # set 是更新部分字段
item: “ABC123”,
“info.publisher”: “2222”,
tags: [ “software” ],
“ratings.1”: { by: “xyz”, rating: 3 }
}
}
)
//更新結果
{
“_id” : 1,
“item” : “ABC123”,
“stock” : 5,
“info” : { “publisher” : “2222”, “pages” : 430 },
“tags” : [ “software” ],
“ratings” : [ { “by” : “ijk”, “rating” : 4 }, { “by” : “xyz”, “rating” : 3 } ],
“reorder” : false
}
//更新全部字段
db.books.update(
{ item: “XYZ123” },
{
item: “XYZ123”,
stock: 10,
info: { publisher: “2255”, pages: 150 },
tags: [ “baking”, “cooking” ]
}
)
//更新結果
{
“_id” : 2,
“item” : “XYZ123”,
“stock” : 10,
“info” : { “publisher” : “2255”, “pages” : 150 },
“tags” : [ “baking”, “cooking” ]
}
// 更新的時候如果數據不存在就插入insert
db.books.update(
{ item: “ZZZ135” },
{
item: “ZZZ135”,
stock: 5,
tags: [ “database” ]
},
{ upsert: true }
)
//更新結果
{
“_id” : ObjectId(“542310906694ce357ad2a1a9”),
“item” : “ZZZ135”,
“stock” : 5,
“tags” : [ “database” ]
}
// 更新多個文件需要設置multi爲true
db.books.update(
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{ multi: true }
)
// upsert 和 multi 結合使用

給定下面的文檔

{
_id: 5,
item: “EFG222”,
stock: 18,
info: { publisher: “0000”, pages: 70 },
reorder: true
}
{
_id: 6,
item: “EFG222”,
stock: 15,
info: { publisher: “1111”, pages: 72 },
reorder: true
}

更新

db.books.update(
{ item: “EFG222” },
{ $set: { reorder: false, tags: [ “literature”, “translated” ] } },
{ upsert: true, multi: true }
)

更新結果

{
“_id” : 5,
“item” : “EFG222”,
“stock” : 18,
“info” : { “publisher” : “0000”, “pages” : 70 },
“reorder” : false,
“tags” : [ “literature”, “translated” ]
}
{
“_id” : 6,
“item” : “EFG222”,
“stock” : 15,
“info” : { “publisher” : “1111”, “pages” : 72 },
“reorder” : false,
“tags” : [ “literature”, “translated” ]
}

如果沒有匹配的文檔就會插入文檔

{
“_id” : ObjectId(“5423200e6694ce357ad2a1ac”),
“item” : “EFG222”,
“reorder” : false,
“tags” : [ “literature”, “translated” ]
}
//更新數組

現有以下數據

db.students.insert([
{ “_id” : 1, “grades” : [ 95, 92, 90 ] },
{ “_id” : 2, “grades” : [ 98, 100, 102 ] },
{ “_id” : 3, “grades” : [ 95, 110, 100 ] }
])

更新下面數據

db.students.update(
{ grades: { $gte: 100 } },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: set: { "grades.[element]" : 100 } },
{
multi: true,
arrayFilters: [ { “element”: { $gte: 100 } } ]
}
)

更新結果

{ “_id” : 1, “grades” : [ 95, 92, 90 ] }
{ “_id” : 2, “grades” : [ 98, 100, 100 ] }
{ “_id” : 3, “grades” : [ 95, 100, 100 ] }
// 更新數組中的字典

現有以下數據

{
“_id” : 1,
“grades” : [
{ “grade” : 80, “mean” : 75, “std” : 6 },
{ “grade” : 85, “mean” : 90, “std” : 4 },
{ “grade” : 85, “mean” : 85, “std” : 6 }
]
}
{
“_id” : 2,
“grades” : [
{ “grade” : 90, “mean” : 75, “std” : 6 },
{ “grade” : 87, “mean” : 90, “std” : 3 },
{ “grade” : 85, “mean” : 85, “std” : 4 }
]
}

更新語句

db.students2.update(
{ },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: set: { "grades.[elem].mean" : 100 } },
{
multi: true,
arrayFilters: [ { “elem.grade”: { $gte: 85 } } ]
}
)

更新結果

{
“_id” : 1,
“grades” : [
{ “grade” : 80, “mean” : 75, “std” : 6 },
{ “grade” : 85, “mean” : 100, “std” : 4 },
{ “grade” : 85, “mean” : 100, “std” : 6 }
]
}
{
“_id” : 2,
“grades” : [
{ “grade” : 90, “mean” : 100, “std” : 6 },
{ “grade” : 87, “mean” : 100, “std” : 3 },
{ “grade” : 85, “mean” : 100, “std” : 4 }
]
}

// 刪除字段使用$unset
db.books.update( { _id: 1 }, { $unset: { tags: 1 } } )

db.users.find()
{ “_id” : 5, “username” : “mengday10” }
db.users.update({“username” : “mengday11”}, { “_id” : 6, “age” : 20, “gender” : 1 }, true)
WriteResult({ “nMatched” : 0, “nUpserted” : 1, “nModified” : 0, “_id” : 6 })
db.users.find()
{ “_id” : 5, “username” : “mengday10” }
{ “_id” : 6, “age” : 20, “gender” : 1 }

db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456”, “age” : 38 }
// 使用KaTeX parse error: Expected '}', got 'EOF' at end of input: … "mengday5"}, {set: {“age”: 18}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456”, “age” : 18 }

// $unset 用於刪除字段

db.users.update({“username”: “mengday5”}, {"$unset": {“age”: 1}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456” }

db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456” }

// $push: 向數組的尾部添加一個元素,如果字段不存在則創建

db.users.update({“username”: “mengday5”}, {“KaTeX parse error: Expected 'EOF', got '}' at position 23: …{"hobby": "mm"}}̲) WriteResult({…push”: {“hobby”: “money”}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456”, “hobby” : [ “mm”, “money” ] }

// $push + $each : 批量push

db.users.update({“username”: “mengday5”}, {“KaTeX parse error: Expected '}', got 'EOF' at end of input: …": {"hobby": {"each”: [“play”, “eat”]}}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456”, “hobby” : [ “mm”, “money”, “play”, “eat” ] }

// $pushAll = $push + $each 批量push

db.users.update({“username”: “mengday5”}, {"$pushAll": {“hobby”: [“drink”, “happy”]}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456”, “hobby” : [ “mm”, “money”, “play”, “eat”, “drink”, “happy” ] }

db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456” }

// $addToSet:不重複的set集合

db.users.update({}, {"$addToSet": {“hobby”: “eat”}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456”, “hobby” : [ “eat” ] }

db.users.update({}, {“KaTeX parse error: Expected '}', got 'EOF' at end of input: …": {"hobby": {"each”: [“eat”, “drink”]}}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456”, “hobby” : [ “eat”, “drink” ] }

// $pop: 彈出數組的頭部元素或尾部元素: -1:頭部,1:尾部

db.users.update({}, {"$pop": {“hobby”: 1}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday5”, “password” : “123456”, “hobby” : [ “eat” ] }

// $pull: 刪除數組中的值

db.lists.insert({“no”: [1, 1, 1, 3]})
WriteResult({ “nInserted” : 1 })
db.lists.update({}, {"$pull": {“no”: 1}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.lists.find()
{ “_id” : ObjectId(“597c0a3087d089dfa7ce1be2”), “no” : [ 3 ] }

// 使用小標或者定位操作符$來操作數組

db.users.find()
{ “_id” : ObjectId(“597c3c1587d089dfa7ce1be3”), “username” : “mengday”, “addresses” : [ { “city” : “shanghai”, “area” : “zhangjiang” }, { “city” : “beijing”, “area” : “chaoyang” } ] }

// 修改內嵌文檔數組中第二個元素的值

db.users.update({“username”: “mengday”}, {"$set": {“addresses.1.area”: “chaoyangqu”}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.findOne()
{
“_id” : ObjectId(“597c3c1587d089dfa7ce1be3”),
“username” : “mengday”,
“addresses” : [
{
“city” : “shanghai”,
“area” : “zhangjiang”
},
{
“city” : “beijing”,
“area” : “chaoyangqu”
}
]
}

// 定位操作符:使: 查詢條件一般是以數組中的元素爲條件,使用符號作爲滿足查詢條件的第一條文檔對應的下標值

db.users.update({“addresses.city”: “beijing”}, {"KaTeX parse error: Expected '}', got 'EOF' at end of input: …": {"addresses..area": “CHAOYANG”}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.findOne()
{
“_id” : ObjectId(“597c3c1587d089dfa7ce1be3”),
“username” : “mengday”,
“addresses” : [
{
“city” : “shanghai”,
“area” : “zhangjiang”
},
{
“city” : “beijing”,
“area” : “CHAOYANG”
}
]
}

// 文檔整體替換

db.users.update({“username”: “mengday5”}, {“age”: 17})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “age” : 17 }

// 第三個參數: 插入或者更新,當_id不存在的時候插入,當_id值存在的時候更新

db.users.update({"_id": 2}, {“username”: “mengday”, “age”: 16}, true)
WriteResult({ “nMatched” : 0, “nUpserted” : 1, “nModified” : 0, “_id” : 2 })
db.users.find()
{ “_id” : 1, “age” : 17 }
{ “_id” : 2, “username” : “mengday”, “age” : 16 }

// 更新

db.users.update({"_id": 2}, {“username”: “mengday2”, “birthday”: new Date()}, true)
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “age” : 17 }
{ “_id” : 2, “username” : “mengday2”, “birthday” : ISODate(“2017-07-25T06:33:10.579Z”) }

db.users.find()
{ “_id” : 1, “username” : “mengday”, “age” : 16 }
{ “_id” : 2, “username” : “mengday2”, “age” : 16 }

// 更新滿足條件的第一條文檔

db.users.update({“age”: 16}, {$set: {“age”: 18}})
WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 })
db.users.find()
{ “_id” : 1, “username” : “mengday”, “age” : 18 }
{ “_id” : 2, “username” : “mengday2”, “age” : 16 }

// 第三個參數:insertOrUpdate, 第四個參數:是否批量更新,true就是更新所有滿足條件的文檔

db.users.update({“age”: {KaTeX parse error: Expected 'EOF', got '}' at position 8: gte: 16}̲}, {set: {“age”: 25}}, false, true)
WriteResult({ “nMatched” : 2, “nUpserted” : 0, “nModified” : 2 })
db.users.find()
{ “_id” : 1, “username” : “mengday”, “age” : 25 }
{ “_id” : 2, “username” : “mengday2”, “age” : 25 }

// 查詢然後更新,更新是整體替換, 如果想更新指定的字段使用$set修改器即可

db.users.findAndModify({
query: { “username”: “mengday”},
update:{
“age”: 20,
“username”: “mengday20”
}
})
{
“_id” : 1,
“username” : “mengday”,
“age” : 20,
“birthday” : ISODate(“2017-07-25T07:05:28.286Z”)
}
db.users.find()
{ “_id” : 1, “age” : 20, “username” : “mengday20” }查詢數據之find

更新數據之updateOne

示例

//數據
{
“_id” : 1,
“grades” : [
{ “grade” : 80, “mean” : 75, “std” : 6 },
{ “grade” : 85, “mean” : 100, “std” : 4 },
{ “grade” : 85, “mean” : 100, “std” : 6 }
]
}
{
“_id” : 2,
“grades” : [
{ “grade” : 90, “mean” : 100, “std” : 6 },
{ “grade” : 87, “mean” : 100, “std” : 3 },
{ “grade” : 85, “mean” : 100, “std” : 4 }
]
}
//更新
try {
db.restaurant.updateOne(
{ “name” : “Central Perk Cafe” },
{ $set: { “violations” : 3 } }
);
} catch (e) {
print(e);
}
//如果匹配到返回結果
{ “acknowledged” : true, “matchedCount” : 1, “modifiedCount” : 1 }
//如果沒有匹配到返回結果
{ “acknowledged” : true, “matchedCount” : 0, “modifiedCount” : 0 }

示例二

{ “_id” : 1, “name” : “Central Perk Cafe”, “Borough” : “Manhattan”, “violations” : 3 },
{ “_id” : 2, “name” : “Rock A Feller Bar and Grill”, “Borough” : “Queens”, “violations” : 2 },
{ “_id” : 3, “name” : “Empire State Pub”, “Borough” : “Brooklyn”, “violations” : “0” }
//更新語句
try {
db.restaurant.updateOne(
{ “name” : “Pizza Rat’s Pizzaria” },
{ $set: {"_id" : 4, “violations” : 7, “borough” : “Manhattan” } },
{ upsert: true }
);
} catch (e) {
print(e);
}
//返回結果
{
“acknowledged” : true,
“matchedCount” : 0,
“modifiedCount” : 0,
“upsertedId” : 4
}
//更新結果
{ “_id” : 1, “name” : “Central Perk Cafe”, “Borough” : “Manhattan”, “violations” : 3 },
{ “_id” : 2, “name” : “Rock A Feller Bar and Grill”, “Borough” : “Queens”, “violations” : 2 },
{ “_id” : 3, “name” : “Empire State Pub”, “Borough” : “Brooklyn”, “violations” : 4 },
{ “_id” : 4, “name” : “Pizza Rat’s Pizzaria”, “Borough” : “Manhattan”, “violations” : 7 }

//更新語句
try {
db.restaurant.updateOne(
{ “violations” : { $gt: 10} },
{ $set: { “Closed” : true } },
{ upsert: true }
);
} catch (e) {
print(e);
}
//返回結果
{
“acknowledged” : true,
“matchedCount” : 0,
“modifiedCount” : 0,
“upsertedId” : ObjectId(“56310c3c0c5cbb6031cafaea”)
}
//更新結果
{ “_id” : 1, “name” : “Central Perk Cafe”, “Borough” : “Manhattan”, “violations” : 3 },
{ “_id” : 2, “name” : “Rock A Feller Bar and Grill”, “Borough” : “Queens”, “violations” : 2 },
{ “_id” : 3, “name” : “Empire State Pub”, “Borough” : “Brooklyn”, “violations” : 4 },
{ “_id” : 4, “name” : “Pizza Rat’s Pizzaria”, “Borough” : “Manhattan”, “grade” : 7 }
{ “_id” : ObjectId(“56310c3c0c5cbb6031cafaea”), “Closed” : true }

更新數組

//準備數據
db.students.insert([
{ “_id” : 1, “grades” : [ 95, 92, 90 ] },
{ “_id” : 2, “grades” : [ 98, 100, 102 ] },
{ “_id” : 3, “grades” : [ 95, 110, 100 ] }
])
//更新語句
db.students.updateOne(
{ grades: { $gte: 100 } },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: set: { "grades.[element]" : 100 } },
{ arrayFilters: [ { “element”: { $gte: 100 } } ] }
)
//更新結果
{ “_id” : 1, “grades” : [ 95, 92, 90 ] }
{ “_id” : 2, “grades” : [ 98, 100, 100 ] }
{ “_id” : 3, “grades” : [ 95, 110, 100 ] }

//更新數組中的字典
db.students2.insert([
{
“_id” : 1,
“grades” : [
{ “grade” : 80, “mean” : 75, “std” : 6 },
{ “grade” : 85, “mean” : 90, “std” : 4 },
{ “grade” : 85, “mean” : 85, “std” : 6 }
]
},
{
“_id” : 2,
“grades” : [
{ “grade” : 90, “mean” : 75, “std” : 6 },
{ “grade” : 87, “mean” : 90, “std” : 3 },
{ “grade” : 85, “mean” : 85, “std” : 4 }
]
}
])
db.students2.updateOne(
{ },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: set: { "grades.[elem].mean" : 100 } },
{ arrayFilters: [ { “elem.grade”: { $gte: 85 } } ] }
)
// 注意只有_id 爲1 的被更新了, 因爲是updateOne操作
{
“_id” : 1,
“grades” : [
{ “grade” : 80, “mean” : 75, “std” : 6 },
{ “grade” : 85, “mean” : 100, “std” : 4 },
{ “grade” : 85, “mean” : 100, “std” : 6 }
]
}
{
“_id” : 2,
“grades” : [
{ “grade” : 90, “mean” : 75, “std” : 6 },
{ “grade” : 87, “mean” : 90, “std” : 3 },
{ “grade” : 85, “mean” : 85, “std” : 4 }
]
}

更新數據之updateMany
//準備數據
{ “_id” : 1, “name” : “Central Perk Cafe”, “violations” : 3 }
{ “_id” : 2, “name” : “Rock A Feller Bar and Grill”, “violations” : 2 }
{ “_id” : 3, “name” : “Empire State Sub”, “violations” : 5 }
{ “_id” : 4, “name” : “Pizza Rat’s Pizzaria”, “violations” : 8 }
//更新
try {
db.restaurant.updateMany(
{ violations: { $gt: 4 } },
{ $set: { “Review” : true } }
);
} catch (e) {
print(e);
}
//返回
{ “acknowledged” : true, “matchedCount” : 2, “modifiedCount” : 2 }
//結果
{ “_id” : 1, “name” : “Central Perk Cafe”, “violations” : 3 }
{ “_id” : 2, “name” : “Rock A Feller Bar and Grill”, “violations” : 2 }
{ “_id” : 3, “name” : “Empire State Sub”, “violations” : 5, “Review” : true }
{ “_id” : 4, “name” : “Pizza Rat’s Pizzaria”, “violations” : 8, “Review” : true }

如果沒有匹配到數據返回

{ “acknowledged” : true, “matchedCount” : 0, “modifiedCount” : 0 }

示例二 upsert

{ “_id” : 92412, “inspector” : “F. Drebin”, “Sector” : 1, “Patrolling” : true },
{ “_id” : 92413, “inspector” : “J. Clouseau”, “Sector” : 2, “Patrolling” : false },
{ “_id” : 92414, “inspector” : “J. Clouseau”, “Sector” : 3, “Patrolling” : true },
{ “_id” : 92415, “inspector” : “R. Coltrane”, “Sector” : 3, “Patrolling” : false }

try {
db.inspectors.updateMany(
{ “Sector” : { $gt : 4 }, “inspector” : “R. Coltrane” },
{ $set: { “Patrolling” : false } },
{ upsert: true }
);
} catch (e) {
print(e);
}
{
“acknowledged” : true,
“matchedCount” : 0,
“modifiedCount” : 0,
“upsertedId” : ObjectId(“56fc5dcb39ee682bdc609b02”)
}

{ “_id” : 92412, “inspector” : “F. Drebin”, “Sector” : 1, “Patrolling” : true },
{ “_id” : 92413, “inspector” : “J. Clouseau”, “Sector” : 2, “Patrolling” : false },
{ “_id” : 92414, “inspector” : “J. Clouseau”, “Sector” : 3, “Patrolling” : true },
{ “_id” : 92415, “inspector” : “R. Coltrane”, “Sector” : 3, “Patrolling” : false },
{ “_id” : ObjectId(“56fc5dcb39ee682bdc609b02”), “inspector” : “R. Coltrane”, “Patrolling” : false }

更新數組

db.students.insert([
{ “_id” : 1, “grades” : [ 95, 92, 90 ] },
{ “_id” : 2, “grades” : [ 98, 100, 102 ] },
{ “_id” : 3, “grades” : [ 95, 110, 100 ] }
])

db.students.updateMany(
{ grades: { $gte: 100 } },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: set: { "grades.[element]" : 100 } },
{ arrayFilters: [ { “element”: { $gte: 100 } } ] }
)

{ “_id” : 1, “grades” : [ 95, 92, 90 ] }
{ “_id” : 2, “grades” : [ 98, 100, 100 ] }
{ “_id” : 3, “grades” : [ 95, 100, 100 ] }

更新數組中的字典

db.students2.insert([
{
“_id” : 1,
“grades” : [
{ “grade” : 80, “mean” : 75, “std” : 6 },
{ “grade” : 85, “mean” : 90, “std” : 4 },
{ “grade” : 85, “mean” : 85, “std” : 6 }
]
},
{
“_id” : 2,
“grades” : [
{ “grade” : 90, “mean” : 75, “std” : 6 },
{ “grade” : 87, “mean” : 90, “std” : 3 },
{ “grade” : 85, “mean” : 85, “std” : 4 }
]
}
])

db.students2.updateMany(
{ },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: set: { "grades.[elem].mean" : 100 } },
{ arrayFilters: [ { “elem.grade”: { $gte: 85 } } ] }
)

{
“_id” : 1,
“grades” : [
{ “grade” : 80, “mean” : 75, “std” : 6 },
{ “grade” : 85, “mean” : 100, “std” : 4 },
{ “grade” : 85, “mean” : 100, “std” : 6 }
]
}
{
“_id” : 2,
“grades” : [
{ “grade” : 90, “mean” : 100, “std” : 6 },
{ “grade” : 87, “mean” : 100, “std” : 3 },
{ “grade” : 85, “mean” : 100, “std” : 4 }
]
}

查詢數據之find
/ 查詢所有, 相當於 select * from users

db.users.find()
{ “_id” : 1, “username” : “mengday”, “age” : 20, “birthday” : ISODate(“2017-07-25T07:05:28.286Z”) }
{ “_id” : 2, “username” : “tom”, “age” : 18, “birthday” : ISODate(“2017-07-25T07:05:52.166Z”) }
{ “_id” : 3, “username” : “xiaohong”, “age” : 28, “birthday” : ISODate(“2017-07-25T07:06:13.741Z”) }

{ “_id” : 4, “username” : “xiaoming”, “age” : 27, “birthday” : ISODate(“2017-07-25T07:06:44.812Z”) }

{ “_id” : 5, “username” : “sunday”, “age” : 37, “birthday” : ISODate(“2017-07-25T07:07:45.420Z”) }

// pretty() 用於格式化查詢的結果

db.users.find().pretty()
{
“_id” : 1,
“username” : “mengday”,
“age” : 20,
“birthday” : ISODate(“2017-07-25T07:05:28.286Z”)
}

{
“_id” : 5,
“username” : “sunday”,
“age” : 37,
“birthday” : ISODate(“2017-07-25T07:07:45.420Z”)
}

// 查詢一條, 相當於select * from users limit 1

db.users.findOne()
{
“_id” : 1,
“username” : “mengday”,
“age” : 20,
“birthday” : ISODate(“2017-07-25T07:05:28.286Z”)
}

// 查詢條件, 相當於 select * from users where age < 20

db.users.find({“age”: {$lt: 20}})
{ “_id” : 2, “username” : “tom”, “age” : 18, “birthday” : ISODate(“2017-07-25T07:05:52.166Z”) }

// 查詢指定的字段,1:代表要查詢的字段,0:代表不要查詢的字段 ,相當於 select username, age from users where age < 20

db.users.find({“age”: {$lt: 20}}, {"_id":0, “username”: 1, “age”: 1})
{ “username” : “tom”, “age” : 18 }

// and 條件,多個條件直接用逗號分開,不需要什麼操作符: 相當於 select * from users where age < 20 and id < 3

db.users.find({“age”: {KaTeX parse error: Expected 'EOF', got '}' at position 7: lt: 30}̲, "_id": {lt: 3 }})
{ “_id” : 1, “username” : “mengday”, “age” : 20, “birthday” : ISODate(“2017-07-25T07:05:28.286Z”) }
{ “_id” : 2, “username” : “tom”, “age” : 18, “birthday” : ISODate(“2017-07-25T07:05:52.166Z”) }

// 同一個字段多個條件: 相當於 select * from users where age > 25 and age < 30

db.users.find({“age”: {$gt: 25, $lt:30 }})
{ “_id” : 3, “username” : “xiaohong”, “age” : 28, “birthday” : ISODate(“2017-07-25T07:06:13.741Z”) }

{ “_id” : 4, “username” : “xiaoming”, “age” : 27, “birthday” : ISODate(“2017-07-25T07:06:44.812Z”) }

// or: 相當於 select * from users where age > 30 or username = ‘tom’

db.users.find({KaTeX parse error: Expected '}', got 'EOF' at end of input: or: [{"age": {gt: 30}}, {“username”: “tom”}]})
{ “_id” : 2, “username” : “tom”, “age” : 18, “birthday” : ISODate(“2017-07-25T07:05:52.166Z”) }
{ “_id” : 5, “username” : “sunday”, “age” : 37, “birthday” : ISODate(“2017-07-25T07:07:45.420Z”) }

// and or 混合使用,相當於 select * from users where id < 4 and (username = ‘mengdat’ or age < 20)

db.users.find({ KaTeX parse error: Expected '}', got 'EOF' at end of input: …ay"}, {"age": {lt: 20}}], “_id”: {$lt: 4} })
{ “_id” : 1, “username” : “mengday”, “age” : 20, “birthday” : ISODate(“2017-07-25T07:05:28.286Z”) }
{ “_id” : 2, “username” : “tom”, “age” : 18, “birthday” : ISODate(“2017-07-25T07:05:52.166Z”) }

// in: 相當於 select * from users where age in (18, 28)

db.users.find({“age”: {$in: [18, 28]}})
{ “_id” : 2, “username” : “tom”, “age” : 18, “birthday” : ISODate(“2017-07-25T07:05:52.166Z”) }
{ “_id” : 3, “username” : “xiaohong”, “age” : 28, “birthday” : ISODate(“2017-07-25T07:06:13.741Z”) }

// 正則表達式不但可以匹配字符串還可以匹配字段值是正則表達式類型的,此時是相等匹配
// 模糊查詢,正則表達式: 以xiao開頭,以ng結尾
// 相當於 select * from users where username like ‘xiao%’ and username like ‘%ng’

db.users.find({“username”: /^xiao/, “username”: /ng$/})
{ “_id” : 3, “username” : “xiaohong”, “age” : 28, “birthday” : ISODate(“2017-07-25T07:06:13.741Z”) }

{ “_id” : 4, “username” : “xiaoming”, “age” : 27, “birthday” : ISODate(“2017-07-25T07:06:44.812Z”) }

db.users.insert({"_id": 6, “username”: “sunday”, “age”: 39, “birthday”: new Date(), “hobby”: ["eat
", “drink”, “play”, “happy”, “money”, “mm”] })
WriteResult({ “nInserted” : 1 })

// 正則表達式忽略大小寫

db.users.find({“username”: {$regex:/sunday/, options:&quot;options:&quot;i"}})
{ “_id” : 5, “username” : “sunday”, “age” : 37, “birthday” : ISODate(“2017-07-25T07:07:45.420Z”) }
{ “_id” : 6, “username” : “SunDay”, “age” : 39, “birthday” : ISODate(“2017-07-25T07:53:16.072Z”), “h
obby” : [ “eat”, “drink”, “play”, “happy”, “money”, “mm” ] }

// 正則表達式用於數組

db.users.find({“hobby”: {$regex: “mm”}})
{ “_id” : 6, “username” : “SunDay”, “age” : 39, “birthday” : ISODate(“2017-07-25T07:53:16.072Z”), “h
obby” : [ “eat”, “drink”, “play”, “happy”, “money”, “mm” ] }

// 正則表達式包含變量時需要使用eval()函數來計算

var username = “sunday”
db.users.find({“username”: {$regex:eval("/" + username + “/i”)}})
{ “_id” : 5, “username” : “sunday”, “age” : 37, “birthday” : ISODate(“2017-07-25T07:07:45.420Z”) }
{ “_id” : 6, “username” : “SunDay”, “age” : 39, “birthday” : ISODate(“2017-07-25T07:53:16.072Z”), “h
obby” : [ “eat”, “drink”, “play”, “happy”, “money”, “mm” ] }

// 數組字段: 值,意思就是這個數組中是否包含該元素,如果包含就是滿足條件的

db.food.insert({“fruit”: [“apple”, “banana”, “cherry”]})
WriteResult({ “nInserted” : 1 })
db.food.find({“fruit”: “banana”})
{ “_id” : ObjectId(“597d353be210addac88b2a36”), “fruit” : [ “apple”, “banana”, “cherry” ] }

// 當值是一個值時是是否包含,當值是數組時就是精確匹配了,此時匹配不到結果

db.food.find({“fruit”: [“apple”, “cherry”]})
// KaTeX parse error: Expected '}', got 'EOF' at end of input: …ind({"fruit": {all: [“apple”, “cherry”]}})
{ “_id” : ObjectId(“597d353be210addac88b2a36”), “fruit” : [ “apple”, “banana”, “cherry” ] }

// 查詢數組中指定的下標對應的值是否和給的值一樣
// 查詢文檔中的fruit中第三個元素的值是cherry的文檔

db.food.find({“fruit.2”: “cherry”})
{ “_id” : ObjectId(“597d353be210addac88b2a36”), “fruit” : [ “apple”, “banana”, “cherry” ] }

// $size: 根據數組的長度進行篩選

db.food.find({“fruit”: {$size: 3}})
{ “_id” : ObjectId(“597d353be210addac88b2a36”), “fruit” : [ “apple”, “banana”, “cherry” ] }

db.food.find()
{ “_id” : ObjectId(“597d353be210addac88b2a36”), “fruit” : [ “apple”, “banana”, “orange”, “cherry” ]

// 返回數組中前兩個元素

db.food.find({}, {“fruit”: {KaTeX parse error: Expected 'EOF', got '}' at position 9: slice: 2}̲}) { "_id" : Ob…slice: -2}})
{ “_id” : ObjectId(“597d353be210addac88b2a36”), “fruit” : [ “orange”, “cherry” ] }
// 偏移下標爲1,取2個長度,相當於 limint 0, 2
db.food.find({}, {“fruit”: {$slice: [1, 2]}})
{ “_id” : ObjectId(“597d353be210addac88b2a36”), “fruit” : [ “banana”, “orange” ] }

db.test.find()
{ “_id” : ObjectId(“597d4342e210addac88b2a37”), “x” : [ 2, 5 ] }
{ “_id” : ObjectId(“597d4350e210addac88b2a38”), “x” : [ 4, 5 ] }
{ “_id” : ObjectId(“597d4367e210addac88b2a39”), “x” : [ 4, 10 ] }
// KaTeX parse error: Expected '}', got 'EOF' at end of input: …t.find({"x": {"elemMatch": {$gt: 5, $lt: 20}}})
{ “_id” : ObjectId(“597d4367e210addac88b2a39”), “x” : [ 4, 10 ] }

// 根據字段的數據類型來查詢,2代碼String

db.users.find({“username”: {$type: 2}})
{ “_id” : 1, “username” : “mengday”, “age” : 20, “birthday” : ISODate(“2017-07-25T07:05:28.286Z”) }
{ “_id” : 2, “username” : “tom”, “age” : 18, “birthday” : ISODate(“2017-07-25T07:05:52.166Z”) }
{ “_id” : 3, “username” : “xiaohong”, “age” : 28, “birthday” : ISODate(“2017-07-25T07:06:13.741Z”) }
{ “_id” : 4, “username” : “xiaoming”, “age” : 27, “birthday” : ISODate(“2017-07-25T07:06:44.812Z”) }
{ “_id” : 5, “username” : “sunday”, “age” : 37, “birthday” : ISODate(“2017-07-25T07:07:45.420Z”) }
{ “_id” : 6, “username” : “SunDay”, “age” : 39, “birthday” : ISODate(“2017-07-25T07:53:16.072Z”), “h
obby” : [ “eat”, “drink”, “play”, “happy”, “money”, “mm” ] }

// 查詢文檔中沒有username字段的或者username的值是null

db.users.find({“username”: null})
// 查詢文檔中存在username字段,並且值是null, KaTeX parse error: Expected '}', got 'EOF' at end of input: …({"username": {in: [null], $exists: true}})
{ “_id” : ObjectId(“597c58f848c373e228a925a6”), “username” : null, “age” : 25 }
{ “_id” : ObjectId(“597c591e48c373e228a925ab”), “username” : null, “age” : 24 }

// 自定義篩選條件,通過js函數返回的boolean值來篩選,可以實現複雜條件的篩選

db.users.find({$where: function(){ return this.username == ‘mengday’ }})
{ “_id” : 1, “username” : “mengday”, “age” : 20, “birthday” : ISODate(“2017-07-25T07:05:28.286Z”) }

// 運行命令: 平常使用的很多命令如db.test.drop()底層都是調用的db.runCommand({“函數名”:參數值})來實現的

db.runCommand({“drop”: “test”})
{ “ns” : “test.test”, “nIndexesWas” : 1, “ok” : 1 }
// db.getLastError 和 db.runCommand({getLastError: 1}) 是一樣的
db.getLastError
db.runCommand({getLastError: 1})

mongo運算符
$eq 等於
$ne 不等於
$gt 大於
$gte 大於等於
$lt 小於
$lte 小於等於
$in 在範圍內
$nin 不在範圍內

查詢集合總數據
db.collection.count()

條件查詢
db.collection.find({ “field” : { $gt: value } } ); // 大於: field > value

allSQLin,in滿(),all匹配所有 這個操作符跟SQL 語法的in 類似,但不同的是, in 只需滿足( )內的某一個值即可, 而all 必須包含[ ]內的所有值,例如:
db.users.find({age : {KaTeX parse error: Expected 'EOF', got '}' at position 13: all : [6, 8]}̲}); 可以查詢出 {name…exists判斷字段是否存在

$exists判斷是否存在
查詢存在字段age 的數據

db.c1.find({age:{$exists:true}});
{ “_id” : ObjectId(“4fb4a773afa87dc1bed9432d”), “age” : 20, “length” : 30 }

null值查詢處理

db.c2.find({age:null})
{ “_id” : ObjectId(“4fc34bb81d8a39f01cc17ef4”), “name” : “Lily”, “age” : null }
{ “_id” : ObjectId(“4fc34c1e1d8a39f01cc17ef6”), “name” : “Tom”, “addr” : 23 }
//需要注意的是 不存在該字段的數據也被認爲是null了,如果你不想這種數據返回,需要的字段值就是精確的null
//請使用exists限制一下
db.c2.find({age:{exists:true,exists:true,eq:null}})

$mod取模運算
查詢age 取模10 等於0 的數據
db.student.find( { age: { $mod : [ 10 , 1 ] } } )

$ne不等於
查詢x 的值不等於3 的數據
db.things.find( { x : { $ne : 3 } } );

KaTeX parse error: Expected '}', got 'EOF' at end of input: …orite_number: {size: 3}}); 能查詢出下面的這條記錄
{name: ‘David’, age: 26, favorite_number: [ 6, 7, 9 ] }
但是db.users.find({favorite_number: {$size: 2}});就無法匹配,因爲數組的長度不匹配

正則表達式匹配查詢
db.users.find({name:/^B./}); 匹配 name字段以 B開頭的數據
db.users.find({name: {$not: /^B.
/}}); 匹配name字段不以B開頭的數據

遊標操作之skip
相當於mysql的 limit 3,5
限制查詢的起始位置,和返回指定的數量的數據
db.users.find().skip(3).limit(5);

查詢結果之排序sort
db.users.find().sort({age: 1}); 以年齡升序排序
db.users.find().sort({age: -1}); 以年齡降序排序

刪除數據之deleteOne

語法:

db.collection.deleteOne(
,
{
writeConcern: ,
collation:
}
)

語法詳解

filter 文件 使用查詢運算符指定刪除條件。若指定一個空文檔則刪除集合中返回的第一個文檔。{ }
writeConcern 文件 可選的。表達寫作關注的文件。省略使用默認寫入問題。使用事務需要注意
collation 文件 可選的。

刪除順序

db.collection.deleteOne刪除與篩選器匹配的第一個文檔。使用屬於唯一索引的字段,例如_id 用於精確刪除。

示例

刪除單個文檔

該orders集合包含具有以下結構的文檔:
{
_id: ObjectId(“563237a41a4d68582c2509da”),
stock: “Brent Crude Futures”,
qty: 250,
type: “buy-limit”,
limit: 48.90,
creationts: ISODate(“2015-11-01T12:30:15Z”),
expiryts: ISODate(“2015-11-01T12:35:15Z”),
client: “Crude Traders Inc.”
}
try {
db.orders.deleteOne( { “_id” : ObjectId(“563237a41a4d68582c2509da”) } );
} catch (e) {
print(e);
}

返回結果

{ “acknowledged” : true, “deletedCount” : 1 }

對於大於這樣有可能會有多個匹配的結果的時候只會刪除匹配的第一個文檔

try {
db.orders.deleteOne( { “expiryts” : { $gt: ISODate(“2015-11-01T12:40:15Z”) } } );
} catch (e) {
print(e);
}
{ “acknowledged” : true, “deletedCount” : 1 }

//集合myColl包含以下文檔:
{ _id: 1, category: “café”, status: “A” }
{ _id: 2, category: “cafe”, status: “a” }
{ _id: 3, category: “cafE”, status: “a” }

刪除數據只deleteMany
db.collection.deleteMany(
,
{
writeConcern: ,
collation:
}
)
必須

示例

該orders集合包含具有以下結構的文檔:
{
_id: ObjectId(“563237a41a4d68582c2509da”),
stock: “Brent Crude Futures”,
qty: 250,
type: “buy-limit”,
limit: 48.90,
creationts: ISODate(“2015-11-01T12:30:15Z”),
expiryts: ISODate(“2015-11-01T12:35:15Z”),
client: “Crude Traders Inc.”
}

// 刪除
try {
db.orders.deleteMany( { “client” : “Crude Traders Inc.” } );
} catch (e) {
print (e);
}
// 返回結果
{ “acknowledged” : true, “deletedCount” : 10 }
// 刪除
try {
db.orders.deleteMany( { “stock” : “Brent Crude Futures”, “limit” : { $gt : 48.88 } } );
} catch (e) {
print (e);
}
//返回結果
{ “acknowledged” : true, “deletedCount” : 8 }

查詢數據的數量之count
db.collection.count(查詢條件,選項)
選項講解:
limit 整數 可選的。要計算的最大文檔數。
skip 整數 可選的。計數前要跳過的文檔數。
hint 字符串或文件 可選的。查詢的索引名稱提示或規範。
maxTimeMS 整數 可選的。允許查詢運行的最長時間。

//在分片羣集上,如果存在孤立文檔或 正在進行塊遷移,
//則db.collection.count()沒有查詢謂詞可能會導致計數 不準確。
//要避免這些情況,請在分片羣集上使用以下 db.collection.aggregate()方法:
db.collection.aggregate( [
{ KaTeX parse error: Expected 'EOF', got '}' at position 18: …unt: "myCount" }̲ ]) 該count階段相當於以下 $group+ $project序列:
db.collection.aggregate( [
{ $group: { _id: null, count: { $sum: 1 } } }
{ $project: { _id: 0 } }
] )

// 對於存在索引{ a: 1, b: 1 }的集合,使用find查詢出數據再count會快一點

使用索引返回計數

db.collection.find( { a: 5, b: 5 } ).count()
db.collection.find( { a: { $gt: 5 } } ).count()
db.collection.find( { a: 5, b: { $gt: 10 } } ).count()

對於不連續的查詢也需要使用返回數據再count

db.collection.find( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
db.collection.find( { a: { $gt: 5 }, b: 5 } ).count()
db.collection.find( { a: 5, b: 5, c: 5 } ).count()

//正常的使用count

查找出orders下面的所有文檔

db.orders.count() # 相當於 db.orders.find().count()不過count是不返回結果的,只返回匹配的數量

而find 是返回結果的,find().count()是將返回的結果統計數量

示例2

db.orders.count( { ord_dt: { $gt: new Date(‘01/01/2012’) } } )

相當於 db.orders.find( { ord_dt: { $gt: new Date(‘01/01/2012’) } } ).count()

遊標操作cursor
var cursor = db.users.find()
while(cursor.hasNext()){
user = cursor.next();
print(user);
}

//遊標遍歷完成之後就會被刪除,繼續使用需要重新查詢
var cursor = db.users.find()
cursor.forEach(function(x){
print(x);
});

//使用limit 查詢兩條文檔
db.users.find({}, {“username”: 1}).limit(2)
{ “_id” : 1, “username” : “mengday” }
{ “_id” : 2, “username” : “tom” }

//分頁第一種方法使用skip和limit,skip指的是offset,相當於select id, username from users limit 2,2
db.users.find({}, {“username”: 1}).skip(2).limit(2)
{ “_id” : 3, “username” : “xiaohong” }
{ “_id” : 4, “username” : “xiaoming” }

查詢操作之排序sort
// 1 代表升序,2代表降序
db.users.find({}, {“username”: 1}).skip(2).limit(2).sort({“age”: 1})
{ “_id” : 4, “username” : “xiaoming” }
{ “_id” : 3, “username” : “xiaohong” }

db.users.find()
{ “_id” : 1, “username” : “mengday1”, “age” : 26, “create_date” : ISODate(“2017-07-30T07:52:33.837Z”) }
{ “_id” : 2, “username” : “mengday2”, “age” : 26, “create_date” : ISODate(“2017-07-30T07:52:43.021Z”) }
{ “_id” : 3, “username” : “mengday3”, “age” : 26, “create_date” : ISODate(“2017-07-30T07:52:53.420Z”) }
{ “_id” : 4, “username” : “mengday4”, “age” : 26, “create_date” : ISODate(“2017-07-30T07:53:00.299Z”) }
{ “_id” : 5, “username” : “mengday5”, “age” : 26, “create_date” : ISODate(“2017-07-30T07:53:07.826Z”) }
{ “_id” : 6, “username” : “mengday6”, “age” : 26, “create_date” : ISODate(“2017-07-30T07:53:13.290Z”) }
{ “_id” : 7, “username” : “mengday7”, “age” : 26, “create_date” : ISODate(“2017-07-30T07:54:36.710Z”) }
{ “_id” : 8, “username” : “mengday8”, “age” : 26, “create_date” : ISODate(“2017-07-30T07:54:40.262Z”) }

var page1 = db.users.find().sort({“create_date”: 1}).limit(5);
var latest = null;
while(page1.hasNext()){
… latest = page1.next();
… print(“page1:” + latest.username);
… }
page1:mengday1
page1:mengday2
page1:mengday3
page1:mengday4
page1:mengday5

查詢操作之聚合
//去重操作
// distinct: 查詢某個字段的所有不重複的值, 相當於 select distinct age from users
db.users.distinct(“age”)
[ 20, 18, 28, 27, 37, 39 ]

//聚合操作
db.orders.find()
{ _id: 1, cust_id: “abc1”, ord_date: ISODate(“2012-11-02T17:04:11.102Z”), status: “A”, amount: 50 }
{ _id: 2, cust_id: “xyz1”, ord_date: ISODate(“2013-10-01T17:04:11.102Z”), status: “A”, amount: 100 }
{ _id: 3, cust_id: “xyz1”, ord_date: ISODate(“2013-10-12T17:04:11.102Z”), status: “D”, amount: 25 }
{ _id: 4, cust_id: “xyz1”, ord_date: ISODate(“2013-10-11T17:04:11.102Z”), status: “D”, amount: 125 }
{ _id: 5, cust_id: “abc1”, ord_date: ISODate(“2013-11-12T17:04:11.102Z”), status: “A”, amount: 25 }

db.orders.aggregate([
{ $match: { status: “A” } },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: group: { _id: "cust_id", total: { sum:&quot;sum: &quot;amount" } } },
// _id指定了根據什麼字段進行分組,這裏根據cust_id字段進行分組
// 給聚合後的結果起一個別名字段 total
// 聚合的方式是求和 $sum ,對 amount字段求和
{ $sort: { total: -1 } } // -1 代表降序
])

{ “_id” : “xyz1”, “total” : 100 }
{ “_id” : “abc1”, “total” : 75 }

//以下聚合操作將選項explain設置 true爲返回有關聚合操作的信息。
db.orders.aggregate(
[
{ $match: { status: “A” } },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: group: { _id: "cust_id", total: { sum:&quot;sum: &quot;amount" } } },
{ $sort: { total: -1 } }
],
{
explain: true
}
)
該操作返回帶有文檔的遊標,該文檔包含有關聚合管道處理的詳細信息,例如,除了其他細節之外,
文檔還可以顯示所使用的操作的索引(如果有的話)。
[1]如果orders集合是分片集合,則文檔還將顯示分片和合並操作之間的分工,以及目標查詢,目標分片。

//例如,以下聚合操作指定遊標的 初始批處理大小0
db.orders.aggregate(
[
{ $match: { status: “A” } },
{ KaTeX parse error: Expected '}', got 'EOF' at end of input: group: { _id: "cust_id", total: { sum:&quot;sum: &quot;amount" } } },
{ $sort: { total: -1 } },
{ $limit: 2 }
],
{
cursor: { batchSize: 0 }
}
)

//集合 mycoll包含以下文檔
db.mycoll.find()
{ _id: 1, category: “café”, status: “A” }
{ _id: 2, category: “cafe”, status: “a” }
{ _id: 3, category: “cafE”, status: “a” }
//以下聚合操作包括排序規則選項:
db.myColl.aggregate(
[ { $match: { status: “A” } }, { KaTeX parse error: Expected '}', got 'EOF' at end of input: group: { _id: "category", count: { $sum: 1 } } } ],
{ collation: { locale: “fr”, strength: 1 } }
);

提示索引
//foodColl使用以下文檔創建集合
db.foodColl.insert([
{ _id: 1, category: “cake”, type: “chocolate”, qty: 10 },
{ _id: 2, category: “cake”, type: “ice cream”, qty: 25 },
{ _id: 3, category: “pie”, type: “boston cream”, qty: 20 },
{ _id: 4, category: “pie”, type: “blueberry”, qty: 15 }
])
//創建以下索引:
db.foodColl.createIndex( { qty: 1, type: 1 } );
db.foodColl.createIndex( { qty: 1, category: 1 } );
//以下聚合操作包括hint強制使用指定索引的選項:
db.foodColl.aggregate(
[ { $sort: { qty: 1 }}, { $match: { category: “cake”, qty: 10 } }, { $sort: { type: -1 } } ],
{ hint: { qty: 1, category: 1 } }
)

//聚合
//db爲video collection爲movies裏面的文檔格式爲:
{
“_id” : ObjectId(“599b3b54b8ffff5d1cd323d8”),
“title” : “Jaws”,
“year” : 1975,
“imdb” : “tt0073195”
}

命令

db.movies.aggregate( [ { $match: { year : 1995 } } ], { comment : “match_all_movies_from_1995” } ).pretty()

查看最近的類似聚合

db.system.profile.find( { “command.aggregate”: “movies”, “command.comment” : “match_all_movies_from_1995” } ).sort( { ts : -1 } ).pretty()

這將以以下格式返回一組探查器結果:

{
“op” : “command” ,
“ns” : “video.movies” ,
“command” : {
“aggregate” : “movies” ,
“pipeline” : [
{
“$ match” : {
“year” : 1995
}
}
],
“comment” : “match_all_movies_from_1995” ,
“cursor” : {

},
“$ db”  : “video” 

},

}

作者:陸_志東
鏈接:https://www.jianshu.com/p/4ecde929b17d
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯繫作者獲得授權並註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章