MongoDB $in 和 Sort , find(), $add,$set(), $map, $addFields, $multiply, update(), updateMany()用法

$in

Syntax{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

$in selects the documents where the field value equals any value in the specified array (e.g. <value1><value2>, etc.)

Consider the following example:

db.inventory.find( { qty: { $in: [ 5, 15 ] } } )

This query selects all documents in the inventory collection where the qty field value is either 5 or 15. Although you can express this query using the [$or](or.html#_S_or) operator, choose the $in operator rather than the [$or](or.html#_S_or) operator when performing equality checks on the same field.

If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (e.g. <value1><value2>, etc.)

Consider the following example:

db.inventory.update( { tags: { $in: ["appliances", "school"] } }, { $set: { sale:true } } )

This [update()](db.collection.update.html#db.collection.update) operation will set the sale field value in the inventory collection where the tags field holds an array with at least one element matching an element in the array ["appliances", "school"].

也可以参考

[find()](db.collection.find.html#db.collection.find), [update()](db.collection.update.html#db.collection.update), [$or]

(or.html#_S_or), [$set](set.html#_S_set).

以上是 MongoDB中文文档 给出的解释和语法

MongoDB sort() 方法

在 MongoDB 中使用 sort() 方法对数据进行排序,sort() 方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列

语法

sort()方法基本语法如下所示:

>db.COLLECTION_NAME.find().sort({KEY:1})

例如:db.getCollection('mongo_test').find().sort({_id:-1})

例如:查詢mongo_test集合 id在170735,19786503,170732,170764,19786435中的数据,并按id降序排列

db.getCollection('mongo_test').find({_id:{$in: [170735,19786503,170732,170764,19786435]}}).sort({_id:-1})

 

 使用Shell中的db.collection.find()方法 对数组字段进行查询操作的示例 mongo

1.查询所有的结果

 2.查询符合条件的记录

 

 3.查询符合条件的指定的列

 4.sql查询条件中的and和or在mongodb中的应用

mongodb中使用and查询的类比语法为:db.col.find({key1:value1, key2:value2}).pretty(),比较简单,只需将多个键值对传入即可

 mongodb中的or语法与and类似,只是是以$or为键传入一个集合的值,具体的语法为db.col.find({$or:[{key1: value1},{key2:value2}]}).pretty()

创建一个temperatures包含摄氏温度的示例集合(如果该集合当前不存在,则插入操作将创建该集合):

 以下db.collection.updateMany()操作使用聚合管道以华氏度的相应温度更新文档:

具体来说,管道包括一个$addFields 阶段,以添加一个新的数组字段tempsF,该字段包含华氏温度。要将tempsC数组中的每个摄氏温度转换为华氏温度,该阶段使用 $map带有$add和的 $multiply表达式。

 

 以下db.collection.updateOne()操作使用聚合管道通过以下方式向文档添加测验分数:_id: 2

 

 

 


版权声明:本文为zuihongyan518原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。