简体   繁体   中英

MongoDB With nested $in and $or

I am using the MongoDB PHP Library and have the following query array

Array
(
  [$and] => Array
    (
      [0] => Array
        (
          [$or] => Array
            (
              [0] => Array
                (
                  [role.name] => Array
                    (
                      [$in] => Array
                        (
                          [0] => 'User'
                          [1] => 'VIP User'
                        )
                    )
                )
              [1] => Array
                (
                  [role._id] => Array
                    (
                      [$in] => Array
                        (
                          [0] => 'User'
                          [1] => 'VIP User'
                        )
                    )
                )
            )
        )
    )
)

Which does not work. However, this does:

Array
(
  [$and] => Array
    (
      [0] => Array
        (
          [role.name] => Array
            (
              [$in] => Array
                (
                  [0] => 'User'
                  [1] => 'VIP User'
                )
            )
        )
    )
)

Any idea what the problem is? (This is an abstracted example)

I don't see a problem with your queries, apart from the redundant $and operator. Consider the following Mongo shell example:

> db.foo.drop()
true
> db.foo.insert({role:{name:"User"}});
> db.foo.insert({role:{name:"Admin"}});
> db.foo.insert({role:{name:"VIP User"}});
> db.foo.find({$or:[{"role.name":{$in:["User", "VIP User"]}}, {"role._id":{$in:["User", "VIP User"]}}]});
{ "_id" : ObjectId("4fea16dcdb49621e28c004a2"), "role" : { "name" : "User" } }
{ "_id" : ObjectId("4fea16e8db49621e28c004a4"), "role" : { "name" : "VIP User" } }
> db.foo.find({$and:[{$or:[{"role.name":{$in:["User", "VIP User"]}}, {"role._id":{$in:["User", "VIP User"]}}]}]});
{ "_id" : ObjectId("4fea16dcdb49621e28c004a2"), "role" : { "name" : "User" } }
{ "_id" : ObjectId("4fea16e8db49621e28c004a4"), "role" : { "name" : "VIP User" } }

Note that there isn't a role._id field in my data, so it was simply ignored.

If you're having trouble with the JavaScript shell, it may be helpful to walk through the examples in the $or and $and documentation. Both operators expect an array as their value, which in turn can contain any number of valid criteria objects.

The main benefit of $and is when you need to satisfy multiple criterion for the same field. If the field names are different, it's equivalent to simply using a criteria object (where keys are implicitly and-ed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM