realtebo
realtebo

Reputation: 25637

Mongo how to search for a field of element of array?

I try to explain

I have a lot of 'companies' in a collection.

each company has a field like this

"carriers" : [
    {
        "priority" : NumberInt(1), 
        "carrier_id" : "a77c9d80-0683-11ec-bec1-074eeabae60b"
    }, 
    {
        "priority" : NumberInt(2), 
        "carrier_id" : "a77d8720-0683-11ec-b6d4-6765509a5216"
    }
]

Having a carrier_id, how can I search every company where carrier_id is equal to searched one?

Upvotes: 0

Views: 53

Answers (3)

mohammad Naimi
mohammad Naimi

Reputation: 2359

as I know you want to search all docs that have specific carrier_id for example "a77c9d80-0683-11ec-bec1-074eeabae60b". so when carrier_id is in array we should use $elemMatch to find value in array. in this query we said mongo find all docs that array of carriers have a carrier_id of "a77c9d80-0683-11ec-bec1-074eeabae60b" and at the end of code I add toArray() to get docs as array

db.collection.find({carriers:{$elemMatch:{carrier_id:"a77c9d80-0683-11ec-bec1-074eeabae60b"}}}).toArray()

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

Upvotes: 1

J.F.
J.F.

Reputation: 15177

If I've understood correctly you can use $filter in a $project stage:

db.collection.aggregate([
  {
    "$project": {
      "carriers": {
        "$filter": {
          "input": "$carriers",
          "as": "c",
          "cond": {
            "$eq": [
              "$$c.carrier_id",
              "a77c9d80-0683-11ec-bec1-074eeabae60b"
            ]
          }
        }
      }
    }
  }
])

Example here

Upvotes: 0

D. SM
D. SM

Reputation: 14480

The dot notation works transparently over array elements. You can do:

{'carriers.carrier_id' => 1}

Upvotes: 1

Related Questions