Abinash Biswal
Abinash Biswal

Reputation: 167

Query for all documents when any of the array element is found in a field in mongodb

I have a document like this:

[
  {
    "id": 1,
    "active": true,
    "key": []
  },
  {
    "id": 2,
    "active": true,
    "key": [
      {
        "code": "fake_code",
        "ids": [
          ""
        ],
        "labels": [
          "d"
        ]
      }
    ]
  },
  {
    "id": 3,
    "active": true,
    "key": [
      {
        "code": "fake_code",
        "ids": [
          ""
        ],
        "labels": [
          "a",
          "b",
          "c"
        ]
      }
    ]
  }
]

I only want to get the id of the documents in which any of the values of the given array(let's say ["a", "b", "c", "d"]) present in labels field in the documents.

That means, since the given array = ["a", "b", "c", "d"], and if you will see the documents, then you can find the document having id = 2 is having ["d"] in the labels field, and the document having id = 3 is having ["a", "b", "c"] in it's labels.

So, the expected output is like,

[
  {
    "id": 2
  },
  {
    "id": 3
  }
]

Currently, I've been using

db.collection.find({
  "key": {
    "$all": [
      {
        "$elemMatch": {
          "ids": {
            "$in": [
              ""
            ]
          },
          "code": "fake_code",
          "labels": {
            "$in": [
              [
                "a",
                "b",
                "c"
              ]
            ]
          }
        }
      }
    ]
  }
},
{
  _id: 0,
  id: 1
})

This query is able to return me only one document having id = 3, because in this case I am using the given array = ["a", "b", "c"]. But is it possible to get all documents according to the given array(like ["a", "b", "c", "d"]), that means if any document is having at least one matching values of the given array then the query should return the id of those documents?

Thanks

Upvotes: 1

Views: 109

Answers (1)

varman
varman

Reputation: 8894

You can use $in. I fyou dont have any condition inside $elemMatch, you can directly access "key.labels":{$in:[....]}

db.collection.find({
  key: {
    $elemMatch: {
      labels: {
        $in: [
          "a",
          "b",
          "c",
          "d"
        ]
      }
    }
  }
},
{
  _id: 0,
  id: 1
})

Working Mongo playground

Upvotes: 1

Related Questions