Supradeep
Supradeep

Reputation: 3266

Mongo Db $in query with multiple keys

I have a Mongo db collection of documents which contains _id , version and many other fields. I have an array of id's like :

["1A", "2b", "3C", "4D"]

If I want all the documents that contain any of the above id's, i could query like :

{
  _id : {
         $in: ["1A", "2b", "3C", "4D"]
        }
}

I'd like to know if we can query with another condition in addition to the _id i.e the above array with condition, something like below :

{
      $in: [{"id":"1A","version":"1.1"},{"id":"2B","version":"2.1"},{"id":"3C","version":"3.1"},{"id":"4D","version":"4.1"}]
        }
}

Example for {"id":"1A","version":"1.1"} : I want all the documents that has id as 1A and version as 1.1. Similarly for all the objects in the array.

Upvotes: 2

Views: 8860

Answers (3)

Ankur Verma
Ankur Verma

Reputation: 5933

You can try something like this:

 db.collection.find(
   {
     //this OR will make sure that you get at any matching combination
     $or:[
       {"<FIELD1>": "<VALUE1.1>", "<FIELD2>": "<VALUE1.2>"},
       {"<FIELD1>": "<VALUE2.1>", "<FIELD2>": "<VALUE2.2>"}
     ]
    }
 )

The documentation of above $and is available here.

Also there are other operators as well, like $or, $not, here

Upvotes: 4

s7vr
s7vr

Reputation: 75984

Showing example with two values. You can add as many you need. Make use of $or and $and operators for multi keys.

find({
    "$or": [{
        "$and": [{
            "_id": "1A"
        }, {
            "version": "1.1"
        }]
    },{
        "$and": [{
            "_id": "2B"
        }, {
            "version": "2.1"
        }]
    }]
})

Update to include the search in the object arrays.

Sample Collection:

db.multikeys.insertMany([{
    _id: 1,
    tags: [{
        _id: "1A",
        version: "1.1"
    }, {
        _id: "2B",
        version: "1.4"
    }]
}, {
    _id: 2,
    tags: [{
        _id: "2B",
        version: "2.1"
    }, {
        _id: "3C",
        version: "3.1"
    }]
}])

Query:

db.multikeys.find({
    tags: {
        $elemMatch: {
            $or: [{
                _id: "2B",
                version: "2.1"
            }, {
                _id: "1A",
                version: "1.1"
            }]
        }
    }
}).pretty()

Sample Output:

{
    "_id": 1,
    "tags": [{
        "_id": "1A",
        "version": "1.1"
    }, {
        "_id": "2B",
        "version": "1.4"
    }]
} {
    "_id": 2,
    "tags": [{
        "_id": "2B",
        "version": "2.1"
    }, {
        "_id": "3C",
        "version": "3.1"
    }]
}

Upvotes: 2

Rahul
Rahul

Reputation: 77926

You need to use $elemMatch to match both the criteria like

db.collection1.find(
   { arrayObjectKeyName: { $elemMatch: { id: "1A", version: "1.1" } } }
)

Sure, here is an example of such

db.collection1.find({ "arrayObjectKeyName": {"$elemMatch":{"id": "1A","version":{"$in":["1.1","1.3","1.9876"]}  }} })

Upvotes: 1

Related Questions