注意
# mongo支持js语法
# 你可以在mongo命令行定义变量
var user = {"name":"nick"}
db.test1.insert(user)
远程连接mongodb
连接方法:
mongo ip:port/dbname -u 用户名 -p 密码
shell连接mongo无法查询解决
# 在mongo数据里命令行输入下面的命令就可以查询了
rs.slaveOk();
查看所有数据库
show dbs
查看所有集合
show tables | show collections
查看当前所在数据库
db
使用数据库
use db_name
删除数据库
db.dropDatabase() # 删除当前正在使用的数据库
使用集合
db.collection_name.find() # 查所有满足条件数据
db.collection_name.findOne() # 查满足条件的一条数据
db.collection_name.count() # 统计集合下面有多少数量的数据
删除集合
db.collection_name.drop()
创建数据库和集合
# 当你使用一个不存在的mongo数据库时,就自动创建了一个mongo数据库
# 同理当你往一个空集合里面插入了一条数据之后就自动创建了一个集合
查看当前数据库状态
db.stats()
查看当前数据库版本
db.version()
备份数据库
导出
mongodump --host IP --port 端口 -u 用户名 -p 密码 -d 数据库 -o 文件路径
导入
mongorestore --host --port -d 文件路径
mongo中的操作符
# 以 $ 开头
$set # 更新字段
$unset # 删除字段
$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(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
// 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 } },
{ $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(
{ },
{ $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 }
// 使用$set修改器修改指定字段, 当字段不存在时会创建并赋值
> db.users.update({"username": "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"}, {"$push": {"hobby": "mm"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find()
{ "_id" : 1, "username" : "mengday5", "password" : "123456", "hobby" : [ "mm" ] }
> db.users.update({"username": "mengday5"}, {"$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"}, {"$push": {"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({}, {"$addToSet": {"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"}, {"$set": {"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": {$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 } },
{ $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(
{ },
{ $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 } },
{ $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(
{ },
{ $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": {$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({$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({ $or: [{"username": "mengday"}, {"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:"$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"]})
// $all: 数组中同时都包含多个元素
> db.food.find({"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": {$slice: 2}})
{ "_id" : ObjectId("597d353be210addac88b2a36"), "fruit" : [ "apple", "banana" ] }
// 返回数组中后两个元素
> db.food.find({}, {"fruit": {$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 ] }
// $elemMatch: 数组中是否有一个元素同时满足所有条件(只要有一个元素满足就能匹配上)
> db.test.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, $in:[null]和username:null 一样的效果
> db.users.find({"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
$all匹配所有
这个操作符跟SQL 语法的in 类似,但不同的是, in 只需满足( )内的某一个值即可,
而$all 必须包含[ ]内的所有值,例如:
db.users.find({age : {$all : [6, 8]}});
可以查询出 {name: 'David', age: 26, age: [ 6, 8, 9 ] }
但查询不出 {name: 'David', age: 26, age: [ 6, 7, 9 ] }$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,$eq:null}})
$mod取模运算
查询age 取模10 等于0 的数据
db.student.find( { age: { $mod : [ 10 , 1 ] } } )
$ne不等于
查询x 的值不等于3 的数据
db.things.find( { x : { $ne : 3 } } );
$size 根据数组的长度进行查询
db.users.find({favorite_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(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)
# 语法详解
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(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)
<filter> 必须
# 示例
该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( [
{ $count: "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" } },
{ $group: { _id: "$cust_id", total: { $sum: "$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" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
],
{
explain: true
}
)
该操作返回带有文档的游标,该文档包含有关聚合管道处理的详细信息,例如,除了其他细节之外,
文档还可以显示所使用的操作的索引(如果有的话)。
[1]如果orders集合是分片集合,则文档还将显示分片和合并操作之间的分工,以及目标查询,目标分片。
//例如,以下聚合操作指定游标的 初始批处理大小0
db.orders.aggregate(
[
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$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" } }, { $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”
},
...
}