为此,只需使用$or一次。让我们创建一个包含文档的集合-
> db.demo551.insertOne({"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36d39e5f92834d7f05e5") } > db.demo551.insertOne({"Name":"Chris Brown"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36d89e5f92834d7f05e6") } > db.demo551.insertOne({"Name":"John Doe"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36de9e5f92834d7f05e7") } > db.demo551.insertOne({"Name":"John Smith"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36e59e5f92834d7f05e8") } > db.demo551.insertOne({"Name":"Carol"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e36ec9e5f92834d7f05e9") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo551.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8e36d39e5f92834d7f05e5"), "Name" : "John" } { "_id" : ObjectId("5e8e36d89e5f92834d7f05e6"), "Name" : "Chris Brown" } { "_id" : ObjectId("5e8e36de9e5f92834d7f05e7"), "Name" : "John Doe" } { "_id" : ObjectId("5e8e36e59e5f92834d7f05e8"), "Name" : "John Smith" } { "_id" : ObjectId("5e8e36ec9e5f92834d7f05e9"), "Name" : "Carol" }
以下是要在同一个键上实现OR条件的查询-
> db.demo551.find({$or:[ ... {"Name" : {$eq : "Carol"}}, ... {Name: {$eq:"John"}} ... ] ... });
这将产生以下输出-
{ "_id" : ObjectId("5e8e36d39e5f92834d7f05e5"), "Name" : "John" } { "_id" : ObjectId("5e8e36ec9e5f92834d7f05e9"), "Name" : "Carol" }