在具有多个条件的 MongoDB 阵列中查找值?
要使用多个条件在数组中查找值,例如,你可以使用 elemMatch与gt 及 $lt 配合使用。语法如下 -
db.yourCollectionName.find({yourFieldName:{$elemMatch:{$gt:yourNegativeValue,$lt:yourPo sitiveValue}}}).pretty();
为了理解上述语法,让我们创建一个包含文档的集合。创建包含文档的集合的查询如下 -
> db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Larry","StudentMarks":[-150,150]}); { "acknowledged" : true, "insertedId" : ObjectId("5c77daf6fc4e719b197a12f5") } > db.findValueInArrayWithMultipleCriteriaDemo.insertOne({"StudentName":"Mike","StudentMarks":[19]}); { "acknowledged" : true, "insertedId" : ObjectId("5c77db09fc4e719b197a12f6") }
借助 find() 方法显示来自集合中的所有文档。查询如下 -
> db.findValueInArrayWithMultipleCriteriaDemo.find().pretty();
以下为输出 -
{ "_id" : ObjectId("5c77daf6fc4e719b197a12f5"), "StudentName" : "Larry", "StudentMarks" : [ -150, 150 ] } { "_id" : ObjectId("5c77db09fc4e719b197a12f6"), "StudentName" : "Mike", "StudentMarks" : [ 19 ] }
下面是如何使用多个条件在数组中查找值的查询。例如,这里我们考虑分数大于 -20 且小于 20 -
> db.findValueInArrayWithMultipleCriteriaDemo.find({StudentMarks:{$elemMatch:{$gt:-20,$lt:20}}}).pretty();
以下为输出 -
{ "_id" : ObjectId("5c77db09fc4e719b197a12f6"), "StudentName" : "Mike", "StudentMarks" : [ 19 ] }
广告