使用AND和OR的MongoDB查询

73

我能在MongoDB查询中使用OR和AND的组合吗?

下面的代码没有按预期工作。

db.things.find({
           $and:[
                {$or:[
                     {"first_name" : "john"}, 
                     {"last_name" : "john"}
                ]},
                {"phone": "12345678"}
            ]});

数据库内容:

> db.things.find();
{ "_id" : ObjectId("4fe8734ac27bc8be56947d60"), "first_name" : "john", "last_name" : "hersh", "phone" : "2222" }
{ "_id" : ObjectId("4fe8736dc27bc8be56947d61"), "first_name" : "john", "last_name" : "hersh", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8737ec27bc8be56947d62"), "first_name" : "elton", "last_name" : "john", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8738ac27bc8be56947d63"), "first_name" : "eltonush", "last_name" : "john", "phone" : "5555" }

查询上述查询时,我什么都没有得到!

> db.things.find({$and:[{$or:[{"first_name" : "john"}, {"last_name" : "john"}]},{"phone": "12345678"}]});
>

我正在使用mongo 1.8.3


我猜测这是由于您正在使用的旧版本MongoDB引起的问题。您的查询似乎可以在2.0.6中正常工作。 - Miikka
5个回答

72
db.things.find({
    $and: [
        {
            $or: [
                {"first_name": "john"},
                {"last_name": "john"}
            ]
        },
        {
            "Phone": "12345678"
        }
    ]
})

AND 接受一个由 2 个表达式组成的数组 OR,phone。
OR 接受一个由 2 个表达式 first_name、last_name 组成的数组。

AND

  • OR

  • first_name

  • last_name

  • 电话号码。

Note: 如果这样不起作用,请升级到最新版本的 MongoDB。


49

更短的方式是使用隐式的AND操作:

db.things.find({
    $or : [ 
        {"first_name": "john"},
        {"last_name": "john"}
    ],
    "phone": "12345678"         
})

$or/$and/$nor 的条目需要是完整的对象。 - moein_py

22

以下是实现该功能的方法(mongodb 3.4)

这是一个好的例子

https://docs.mongodb.com/manual/reference/operator/query/and/#and-queries-with-multiple-expressions-specifying-the-same-operator

        db.getCollection('tbl_menu_items').find({
        $and : [
            { $or : [ { price : 0.99 }, { price : 1.99 } ] },
            { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
        ]
    } )

此查询将选择所有文档,其中:

价格字段值等于0.99或1.99,并且销售字段值等于true或qty字段值小于20。

以下是$and条件与$or查询匹配任何条件的示例

考虑以下查询...


db.getCollection('tbl_menu_items').find(
{ '$or': [ { '$and': [ { location: { '$in': [ ObjectId("588054c63879f2e767a1d553") ] } }, { is_ryward: 1 }, { points_reqiured_to_redeem_reward: { '$lte': 500 } } ] }, { '$and': [ { location: { '$in': [ ObjectId("588054c63879f2e767a1d553") ] } }, { is_freebie: 1 } ] } ] } )

此查询将选择所有文档,其中:

location数组为588054c63879f2e767a1d553,is_ryward = 1且points_reqiured_to_redeem_reward < 500

location数组为588054c63879f2e767a1d553,is_freebie为1。


14

我认为$and只支持MongoDB v2.0+。我很惊讶控制台一开始就接受了这个表达式。我将尝试在我的1.8服务器上重新创建。

还可以查看10Gen的高级查询文档了解$and。

更新

我将您的示例数据输入v1.8x和v2.0x MongoDB服务器。查询在v2.0x上运行并在v1.8x上失败。这证实了我的(和Miikka的)猜测,即问题出现在$and和您的服务器版本之间。

我在网上找到了一个(可以说)聪明的解决方法here。希望这能帮到您。

-SethO


0

你可以简单地像这样编写你的查询:

const query = {};
query['phone'] = '12345678';
query['$or'] = [
  { "first_name": "john" },
  { "last_name": "john" }
];
db.things.find(query);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接