How to get specified data from array object field with specific condition

This the example of my mongodb data:

[{
  "_id": {
    "$oid": "5f9956d8430bef10e05aaffa"
  },
  "_userId": {
    "$oid": "5f89871cea073c27bc192088"
  },
  "username": "ferdinand",
  "connections": [
    {
      "_id": {
        "$oid": "5f9956d8430bef10e05aaffb"
      },
      "_userIdCon": {
        "$oid": "5f8d0ccff7074616e46cf925"
      },
      "username_con": "haleluya",
      "connection_type": 0
    },
    {
      "_id": {
        "$oid": "5f9a7e6dd8bbea1ae0221367"
      },
      "_userIdCon": {
        "$oid": "5f6494c327900b20ec9f0f5b"
      },
      "username_con": "andibel",
      "connection_type": 2
    },
    {
      "_id": {
        "$oid": "5f9fbe785e35584568cfb3fc"
      },
      "_userIdCon": {
        "$oid": "5f682e897a2042380494a854"
      },
      "username_con": "budinam",
      "introduction_con": "ini isi pesan saya ya fer dari budi",
      "connection_type": 0
    }
  ],|
....
}] 

I want to get the data with criteria “userId : 5f89871cea073c27bc192088”
then return sub fields of connections that have “connection_type: 0”
and it just return several data according to the request (limit options)

I don’t know how to do this in mongodb.
I am using mongoose.

I have tried this codes:

Connection.findOne({ _userId: userId }, {"connections": { $slice : [startLoad, limitLoad] }});

But, it just give me the data without filtering “connection_type: 0”

How to add filter “connection_type: 0” ?

Hello @Cakkavati_Kusuma, welcome to the MongoDB community forum.

You can use the $ projection operator. This will return the first matching sub-document of connections array with the matching connection_type value.

You can also use the $elemMatch (projection operator) to get the same result.

1 Like