如何获取 MongoDB 查询的逆结果?
How to take the inverse results of a MongoDB query?
我有一个问题,
SomeCollection.collection.find(:$or => [{tags:'cool'},{tags:'awesome'},{tags:'neat'},...])
我想修改对面的合集。所以除了在前面的语句中找到的元素之外的所有元素。所以在这个例子中,我想要所有不是 tags:'cool' || tags:'awesome' || tags:'neat' || ...
的结果。
我试过 SomeCollection.collection.find(:$not => {:$or => [{tags:'cool'},{tags:'awesome'},{tags:'neat'},...]})
,但出现了语法错误。我也在考虑 SomeCollection.collection.find(:$and => [{tags:{:$ne => 'cool'}}, {tags:{:$ne => 'awesome'}}, {tags:{:$ne => 'neat'}}])
,它是显式逆运算并给出了正确答案。有获取逆向集合的捷径吗?
您可以在查询中使用 $ne。
SomeCollection.collection.find($or : [ {tags: {$ne:'cool}}, ..]
由于您正在比较同一字段的值,因此您甚至可以使用 $nin。查询现在看起来像,
SomeCollection.collection.find($or : [ {tags : {$nin : ['cool','awesome',..]} .. ]
我有一个问题,
SomeCollection.collection.find(:$or => [{tags:'cool'},{tags:'awesome'},{tags:'neat'},...])
我想修改对面的合集。所以除了在前面的语句中找到的元素之外的所有元素。所以在这个例子中,我想要所有不是 tags:'cool' || tags:'awesome' || tags:'neat' || ...
的结果。
我试过 SomeCollection.collection.find(:$not => {:$or => [{tags:'cool'},{tags:'awesome'},{tags:'neat'},...]})
,但出现了语法错误。我也在考虑 SomeCollection.collection.find(:$and => [{tags:{:$ne => 'cool'}}, {tags:{:$ne => 'awesome'}}, {tags:{:$ne => 'neat'}}])
,它是显式逆运算并给出了正确答案。有获取逆向集合的捷径吗?
您可以在查询中使用 $ne。
SomeCollection.collection.find($or : [ {tags: {$ne:'cool}}, ..]
由于您正在比较同一字段的值,因此您甚至可以使用 $nin。查询现在看起来像,
SomeCollection.collection.find($or : [ {tags : {$nin : ['cool','awesome',..]} .. ]