如何实现 MongoDB $or 查询?
MongoDB 中 $or 查询的语法如下 −
db.yourCollectionName.find({ $or : [ { "yourFieldName" : "yourValue1" }, {"yourFieldName":"yourValue2"},...........N ] } ).pretty();
为了理解这个概念,让我们创建一个带有文档的集合。创建带文档的集合的查询如下 −
> db.orDemo.insertOne({"UserName":"Larry","UserAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9491fd4cf1f7a64fa4df4c") } > db.orDemo.insertOne({"UserName":"David","UserAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c9492074cf1f7a64fa4df4d") } > db.orDemo.insertOne({"UserName":"Mike","UserAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c94920e4cf1f7a64fa4df4e") } > db.orDemo.insertOne({"UserName":"Sam","UserAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5c9492144cf1f7a64fa4df4f") } > db.orDemo.insertOne({"UserName":"Carol","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c94921d4cf1f7a64fa4df50") } > db.orDemo.insertOne({"UserName":"Bob","UserAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c94922c4cf1f7a64fa4df51") }
使用 find() 方法显示来自集合的所有文档。查询如下 −
> db.orDemo.find().pretty();
以下是输出
{ "_id" : ObjectId("5c9491fd4cf1f7a64fa4df4c"), "UserName" : "Larry", "UserAge" : 23 } { "_id" : ObjectId("5c9492074cf1f7a64fa4df4d"), "UserName" : "David", "UserAge" : 21 } { "_id" : ObjectId("5c94920e4cf1f7a64fa4df4e"), "UserName" : "Mike", "UserAge" : 25 } { "_id" : ObjectId("5c9492144cf1f7a64fa4df4f"), "UserName" : "Sam", "UserAge" : 20 } { "_id" : ObjectId("5c94921d4cf1f7a64fa4df50"), "UserName" : "Carol", "UserAge" : 24 } { "_id" : ObjectId("5c94922c4cf1f7a64fa4df51"), "UserName" : "Bob", "UserAge" : 22 }
以下是 $or 查询
> db.orDemo.find({ $or : [ { "UserName" : "Carol" }, {"UserName":"Larry"} ] } ).pretty();
以下是输出
{ "_id" : ObjectId("5c9491fd4cf1f7a64fa4df4c"), "UserName" : "Larry", "UserAge" : 23 } { "_id" : ObjectId("5c94921d4cf1f7a64fa4df50"), "UserName" : "Carol", "UserAge" : 24 }
广告