0

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?

2 Answers2

1

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)

mickl
  • 48,568
  • 9
  • 60
  • 89
  • Thank you so much! It works! – Nody Risky Pratomo May 07 '18 at 16:02
  • I'm sorry I have question again. What if i want to get dinas where id is "5aeffdb80e006205640052ff_5af0101d0e006205640053078" ? I try using that code, but it didn't give output – Nody Risky Pratomo May 07 '18 at 16:47
  • @NodyRiskyPratomo just to clarify: first argument of find method checks if any item in dinas has specified id and returns entire document, second argument filters nested array and returns first matching element. Did you try: `db.users.find({"dinas.id": "5aeffdb80e006205640052ff_5af0101d0e006205640053078"}, { "dinas": { $elemMatch: { id: "5aeffdb80e006205640052ff_5af0101d0e006205640053078" } } });` – mickl May 07 '18 at 17:21
  • Eh.. seems like i had typo on my query. so it didn't give me back the output hehe. Your code is works! thanks! – Nody Risky Pratomo May 07 '18 at 18:01
0

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'
        }
    }
});
thepanuto
  • 783
  • 5
  • 17