Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb : How to select objects where an array contains only a specific field?

Tags:

mongodb

I have two objects :

{
        "_id" : ObjectId("54be5f5528c13bfc3409e8c2"),
        "name" : "Antonio",
        "lastname" : "de Cabezón",
        "by" : 1510,
        "dy" : 1566,
        "country" : "spain",
        "genre" : [
                "classical",
                "baroque"
        ]
}
{
        "_id" : ObjectId("54be5f5528c13bfc3409e8c1"),
        "name" : "Guillaume-Antoine",
        "lastname" : "Calvière",
        "by" : 1695,
        "dy" : 1755,
        "country" : "france",
        "genre" : [
                "baroque"
        ]
}

When i do a db.currentdb.find({genre: 'baroque'}), it returns me the first object too.

I'd like to fetch only the object where the genre is only "baroque". What would be the proper way to do it ?

like image 249
Aod Ren Avatar asked Feb 24 '16 15:02

Aod Ren


1 Answers

You could try

db.currentdb.find({genre: ['baroque']})

Also, take a look to the documentation:

https://docs.mongodb.org/manual/reference/method/db.collection.find/

like image 123
robertsan Avatar answered Nov 15 '22 09:11

robertsan