mongoose 操作符

本文详细介绍了MongoDB中的一些操作符,如$currentDate用于设置当前时间,$push用于数组操作,$expr和$setIsSubset配合使用进行复杂查询,$where用于实现复杂查询条件,以及$arrayElemAt、$$root、$min/$max在不同场景的应用。还涵盖了数组操作、字段删除和对象转换的相关操作符。
摘要由CSDN通过智能技术生成

$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" } } }
   ]
)
Mongoose是一个基于MongoDB的Node.js对象模型工具,它为处理MongoDB数据库提供了更丰富的JavaScript对象模型和方便的方法。在Mongoose中,数组操作是非常常见的,特别是在处理嵌套数据或集合型的数据结构时。 **Mongoose数组操作:** 1. **Schema定义**: 在Mongoose schema中,你可以直接定义一个字段为数组类型,如`{ name: [String] }`,这表示该字段将存储一个字符串类型的数组。 2. **动态路径(Dynamic Paths)**: Mongoose支持动态路径,这意味着你可以使用变量名访问数组中的元素,例如`doc['arrayField'][index]`。 3. **push/pop方法**: Mongoose模型实例提供了`push`和`pop`方法用于向数组添加或删除元素,如`model.arrayField.push(newElement)`。 4. **slice/sliceIndex方法**: 你可以像JavaScript数组一样使用`slice`和索引操作,比如`model.arrayField.slice(start, end)`。 5. **$[]操作符**: MongoDB查询中,可以使用`$[]`操作符来查询数组内的值,Mongoose也支持这种写法,如`Model.find({ 'arrayField.$': value })`。 6. **$pull/$pullAll操作符**: 可以用来从数组中移除满足条件的元素,如`model.arrayField.pull(value)`或`model.arrayField.pullAll(arrayToRemove)`。 7. **populate方法**: 如果数组包含关联文档的引用,可以使用`populate`方法来填充这些关联数据。 **相关问题--:** 1. Mongoose如何处理数组的嵌套查询? 2. 如何在Mongoose中对数组进行批量修改操作? 3. 如何使用Mongoose避免数组更新时的冲突?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值