$currentDate
db.getCollection('test').update({name:"shi"},{ $currentDate: {createdAt: true}}) 将时间类型的一个字段修改成当前时间
$push
db.students.update({ name: "joe" }, { $push: { scores: 1 } }) 在scores数组末尾添加一个元素,push只能添加一个
db.students.update(
{ name: "joe" },
{ $push: { scores: { $each: [ 90, 92, 85 ] } } }
) push添加多个需要使用$each
以前还有pushAll,现在已经被push+each代替了
$addToSet
db.inventory.update(
{ _id: 2 },
{ $addToSet: { tags: "camera" } }
) 向一个数组添加一个元素,前提是当前数组中并没有这个元素,如果有就不添加
db.inventory.update(
{ _id: 2 },
{ $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } }
)添加多个需要使用$each操作符
$expr, $setIsSubset 目标字段是查询参数的子集
> db.product.find()
{ "_id" : ObjectId("5d676f5f8b820718b993cd35"), "name" : 1, "vals" : [ "A", "B" ] }
{ "_id" : ObjectId("5d676fbc8b820718b993cd36"), "name" : 2, "vals" : [ "D", "C" ] }
{ "_id" : ObjectId("5d676fc98b820718b993cd37"), "name" : 3, "vals" : [ "A", "D" ] }
db.product.find( { $expr: { $setIsSubset: [ "$vals", ["A","B","D"] ] } } ) 查询要求cals是["A","B","D"]的子集
结果:
{ "_id" : ObjectId("5d676f5f8b820718b993cd35"), "name" : 1, "vals" : [ "A", "B" ] }
{ "_id" : ObjectId("5d676fc98b820718b993cd37"), "name" : 3, "vals" : [ "A", "D" ] }
$where 当一个查询比较复杂的时候,没有相应的运算符,可以使用function来完成一个复杂的查询条件
db.getCollection('apis').find({$where:function() { 这个查询也是实现了被查询文档的a字段的数组是[1,2,3,4]的子集
for (var num of this.a) {
if(![1,2,3,4].includes(num))return false
}
return true;
}})
$arrayElemAt 返回数组指定位置的元素
{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] } 返回
1
{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] } 返回
2
{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] }
数组越界无返回
{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
{ "_id" : 2, "name" : "li", favorites: [ "apples", "pudding", "pie" ] }
{ "_id" : 3, "name" : "ahn", favorites: [ "pears", "pecans", "chocolate", "cherries" ] }
{ "_id" : 4, "name" : "ty", favorites: [ "ice cream" ] }
db.users.aggregate([
{
$project:
{
name: 1,
first: { $arrayElemAt: [ "$favorites", 0 ] },
last: { $arrayElemAt: [ "$favorites", -1 ] }
}
}
])
{ "_id" : 1, "name" : "dave123", "first" : "chocolate", "last" : "apples" }
{ "_id" : 2, "name" : "li", "first" : "apples", "last" : "pie" }
{ "_id" : 3, "name" : "ahn", "first" : "pears", "last" : "cherries" }
{ "_id" : 4, "name" : "ty", "first" : "ice cream", "last" : "ice cream" }
$$root 引用当前管道处理的顶级文档,下面看例子
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
db.books.aggregate(
[
{ $group : { _id : "$author", books: { $push: "$$ROOT" } } }
]
)