Thánh Ma
Thánh Ma

Reputation: 133

How can I provide multiple criteria for an attribute within an element of array in mongo query?

I have a collection with following documents:


    {
       "_id": 1,  
       "books": [  
         {  
           "id":"Sherlock Holmes",  
           "category":"Novel"  
         },  
         {  
           "id":"10 tips for cook",  
           "category":"Tips"  
         }  
       ]  
    },  
    {  
       "_id": 2,  
       "books": [    
         {
           "id":"10 tips for cook",  
           "category":"Tips"
         }  
        ]  
    },  
    {
       "_id": 3,  
       "books": [  
         {  
           "id":"Sherlock Holmes",  
           "category":"Novel"  
         }  
       ]  
    }

I want to query document contains both books with id "Sherlock Holmes" and "10 tips for cook", where its "_id" is 1.

I've tried with $in and $elemMatch but the results are those three. I only need one in this case.

Do you have any solutions?

Upvotes: 1

Views: 100

Answers (2)

Toan Nguyen
Toan Nguyen

Reputation: 11601

Because _id is unique in a MongoDB collection, so you can just query

db.myCollection.find({_id:1})

And if you don't want the whole document to be returned, you can use projection

db.myCollection.find({_id:1},{_id:0, books:1})

Upvotes: 0

thegreenogre
thegreenogre

Reputation: 1579

Use the $and operator to search for the same field with multiple expression.

db.coll.find({
    '$and': [
        {'books.id': 'Sherlock Holmes'},
        {'books.id': '10 tips for cook'}
    ]
})

Result:

{
    "_id" : 1,
    "books" : [ 
        {
            "id" : "Sherlock Holmes",
            "category" : "Novel"
        }, 
        {
            "id" : "10 tips for cook",
            "category" : "Tips"
        }
    ]
}

Upvotes: 4

Related Questions