例如,要在具有多个条件的数组中查找值,可以将$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()method的帮助下显示集合中的所有文档。查询如下-
> 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
]
}