i have data in my collection called users like this
{
"_id" : ObjectId("5aeffdb80e006205640052ff"),
"name" : "KOTA AMBON",
"email" : "ambon@gmail.com",
"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?
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)