反转MongoDB查询的结果(与$ and操作相反)?
要反转结果(即与$and相反),请使用$OR和$ne。首先让我们创建一个包含文档的集合-
> db.demo4.insert({uid:1,"Name":"Chris","Age":22}); WriteResult({ "nInserted" : 1 }) > db.demo4.insert({uid:2,"Name":"David","Age":21}); WriteResult({ "nInserted" : 1 }) > db.demo4.insert({uid:3,"Name":"Bob","Age":23}); WriteResult({ "nInserted" : 1 }) > db.demo4.insert({uid:1,"Name":"Carol","Age":20}); WriteResult({ "nInserted" : 1 })
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.demo4.find();
这将产生以下输出-
{ "_id" : ObjectId("5e0a1da125ddae1f53b62221"), "uid" : 1, "Name" : "Chris", "Age" : 22 } { "_id" : ObjectId("5e0a1db025ddae1f53b62222"), "uid" : 2, "Name" : "David", "Age" : 21 } { "_id" : ObjectId("5e0a1dc225ddae1f53b62223"), "uid" : 3, "Name" : "Bob", "Age" : 23 } { "_id" : ObjectId("5e0a1dd225ddae1f53b62224"), "uid" : 1, "Name" : "Carol", "Age" : 20 }
这是获取反转结果的查询-
> db.demo4.find({uid:2,$or: [{"Name": {$ne: "Carol"}}, {"Age": {$ne: 21}}]});
这将产生以下输出-
{ "_id" : ObjectId("5e0a1db025ddae1f53b62222"), "uid" : 2, "Name" : "David", "Age" : 21 }