如何在 MongoDB 中实现 $or 运算符
使用 MongoDB 中的 $or 运算符求值一个或多个表达式。以下是语法 −
db.yourCollectionName.find({ $or: [{ "yourFieldName": yourValue1 }, { "yourFieldName": yourValue2} ] } ).pretty();
让我们首先使用文档创建一个集合 −
> db.orOperatorDemo.insertOne({"StudentNames":["John","Carol","Sam"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b80a6d78f205348bc61b") } > db.orOperatorDemo.insertOne({"StudentNames":["Robert","Chris","David"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b8266d78f205348bc61c") } > db.orOperatorDemo.insertOne({"StudentNames":["John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6b8346d78f205348bc61d") }
以下是使用 find() 方法在集合中显示所有文档的查询 −
> db.orOperatorDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd6b80a6d78f205348bc61b"), "StudentNames" : [ "John", "Carol", "Sam" ] } { "_id" : ObjectId("5cd6b8266d78f205348bc61c"), "StudentNames" : [ "Robert", "Chris", "David" ] } { "_id" : ObjectId("5cd6b8346d78f205348bc61d"), "StudentNames" : [ "John" ] }
以下是 $or 运算符语法查询 −
> db.orOperatorDemo.find({ $or: [{ "StudentNames": "Carol" }, { "StudentNames": "John"} ] } ).pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd6b80a6d78f205348bc61b"), "StudentNames" : [ "John", "Carol", "Sam" ] } { "_id" : ObjectId("5cd6b8346d78f205348bc61d"), "StudentNames" : [ "John" ] }
广告