1

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?

2
  • What MongoDB version are you using? Commented May 15, 2015 at 8:48
  • I use MongoDB v2.4.5 Commented May 15, 2015 at 10:36

2 Answers 2

4

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"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

0

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})

1 Comment

I need it returns a list that match my criteria. The result should be a list. In this case, the list contains one element only :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.