反转MongoDB查询结果/反对$和操作

时间:2015-05-25 15:10:36

标签: mongodb

这是我的收藏:

{ _id: "539b6502e9630311ad000033", user: "dummy1", x: 1, y: 1 }

{ _id: "539b64c2bdf763720900003e", user: "", x: 0, y: 1 }

{ _id: "539b653ad2a87581ff00000b", user: "dummy3", x: 1, y: 0 }

{ _id: "cPtudQJyKxffCgaZ9", user: "", x: 2, y: 5 }

{ _id: "Br8tCEwhrhG5tKwdJ", user: "dummy1", x: 1, y: 14 }

{ _id: "9AoLD6nLRnhdRfxPw", user: "dummy1", x: 8, y: 15 }

如何查询包含{x: "1", y: "1"}的<{1}}以外的所有文档?

我正在寻找相反的:

user: "dummy1"

返回:

find({user: "dummy1", "$and": [{x: 1}, {y: 1}]}).limit(10)

我的猜测是:

{_id: "539b6502e9630311ad000033", user: "dummy1", x: 1, y: 1}

返回:未找到任何文件。

1 个答案:

答案 0 :(得分:3)

要取消布尔AND,您可以使用OR来否定每个术语:

db.test.find({user: 'dummy1', $or: [{x: {$ne: 1}}, {y: {$ne: 1}}]})

哪个输出:

{
    "_id" : "Br8tCEwhrhG5tKwdJ",
    "user" : "dummy1",
    "x" : 1,
    "y" : 14
}
{
    "_id" : "Br8tCEwhrhG5tKwdx",
    "user" : "dummy1",
    "x" : 3,
    "y" : 5
}