get data from nested documents in mongodb / find is not working

656 Views Asked by At

i have data in my collection called users like this

{
    "_id" : ObjectId("5aeffdb80e006205640052ff"),
    "name" : "KOTA AMBON",
    "email" : "[email protected]",
    "password" : "$2y$10$VVaGAVniUbgBnDw6x5yZ0uAvJDGa5ekmVPJk/1Lubz5yKzZ75opo2",
    "updated_at" : ISODate("2018-05-07T07:18:16Z"),
    "created_at" : ISODate("2018-05-07T07:18:16Z"),
    "dinas" : [
            {
                    "id" : "5aeffdb80e006205640052ff_5af0101d0e00620564005307",
                    "nama_dinas" : "dinas perikanan",
                    "deskripsi_dinas" : "dinas untuk ikan",
                    "keyword" : "ikan"
            },
            {
                    "id" : "5aeffdb80e006205640052ff_5af010390e00620564005308",
                    "nama_dinas" : "dinas perhubungan",
                    "deskripsi_dinas" : "dinas untuk hubungan",
                    "keyword" : "jalan"
            }
    ]

}

I want to get dinas attribute where id is `"5aeffdb80e006205640052ff_5af0101d0e00620564005307"

I had using function db.users.find('dinas.id', '5aeffdb80e006205640052ff_5af0101d0e00620564005307') but the output still called all elements in dinas like i wrote above.

Did i do something wrong?

2

There are 2 best solutions below

4
mickl On BEST ANSWER

Filtering in MongoDB (using find) will always return entire document, you have to add projection as a second argument of a find method like below:

db.users.find({"dinas.id": "5aeffdb80e006205640052ff_5af0101d0e00620564005307"},
{ "dinas": { $elemMatch: { id: "5aeffdb80e006205640052ff_5af0101d0e00620564005307" } } });

$elemMatch in projection will filter your nested array and return first matching element (that's fine assuming your ids are unique)

2
thepanuto On

You need to take a look at array querying. The problem is that your dinas is a array of objects, and you're trying to query it as a object directly.

Probably $elemMatch will help you. Something like:

db.users.find({
    dinas: {
        $elemMatch: {
            id: 'youridhere'
        }
    }
});