MongoDB 查询在 find() 中实现 OR 运算符
让我们创建一个带有文档的集合 -
> db.demo78.insertOne({"Name1":"Chris","Name2":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd99c71bf0181ecc4228f") } > db.demo78.insertOne({"Name1":"Bob","Name2":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd9ac71bf0181ecc42290") } > db.demo78.insertOne({"Name1":"David","Name2":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd9b671bf0181ecc42291") } > db.demo78.insertOne({"Name1":"Jace","Name2":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2bd9bf71bf0181ecc42292") }
使用 find() 方法显示集合中的所有文档 -
> db.demo78.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e2bd99c71bf0181ecc4228f"), "Name1" : "Chris", "Name2" : "Mike" } { "_id" : ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1" : "Bob", "Name2" : "Carol" } { "_id" : ObjectId("5e2bd9b671bf0181ecc42291"), "Name1" : "David", "Name2" : "Sam" } { "_id" : ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1" : "Jace", "Name2" : "John" }
以下是 find() 中实现 OR 运算符的查询 -
> db.demo78.find({$or: [{"Name1": "Bob"}, {Name2: "John"}] });
这将产生以下输出 -
{ "_id" : ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1" : "Bob", "Name2" : "Carol" } { "_id" : ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1" : "Jace", "Name2" : "John" }
广告