在具有多個條件的 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 ] }
廣告