Michael Royf
Michael Royf

Reputation: 127

MongoDB add matched key to list after query

I have a Document in MongoDB with a list of Embedded Documents. let's take a simplified example of a car document with a list of tires:

{
    "make": "Toyota",
    "color": "blue",
    "tires": [{
        "make": "Mishlen",
        "size": 185
    }, {
        "make": "Mishlen",
        "size": 210
    }]
}

When I ran the following query to find all cars with tire size below 200 I get the same document back but I don't know which of the tires matched the query.

{"tires.size": {$gt: 200}}

I'm trying to achive some kind of this result back:

{
    "make": "Toyota",
    "color": "blue",
    "tires": [{
        "make": "Mishlen",
        "size": 185,
        "matched": true
    }, {
        "make": "Mishlen",
        "size": 210,
        "matched": false
    }]
}

This way I can tell which of the tires matched my query. What is the best way to achive this kind of result? in terms of performance.

Upvotes: 2

Views: 81

Answers (2)

user9408899
user9408899

Reputation: 4540

You can use $cond (aggregation) to add a new Boolean value.

db.collection.aggregate([
  {
    $addFields: {
      tires: {
        $map: {
          input: "$tires",
          in: {
            make: "$$this.make",
            size: "$$this.size",
            matched: {
              $cond: {
                if: {
                  $lt: [
                    "$$this.size",
                    200
                  ]
                },
                then: true,
                else: false
              }
            }
          }
        }
      }
    }
  }
])

Results:

[
  {
    "color": "blue",
    "make": "Toyota",
    "tires": [
      {
        "make": "Mishlen",
        "matched": true,
        "size": 185
      },
      {
        "make": "Mishlen",
        "matched": false,
        "size": 210
      }
    ]
  }
]

Live demo: MongoPlayground

Upvotes: 0

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17925

Please try this :

db.yourCollectionName.aggregate([
    { $addFields: {
        tires: {$filter: {
            input: '$tires',
            as: 'each',
            cond: {$lt: ['$$each.size', 200]}
        }}
    }}
])

Collection Data :

{
    "make": "Toyota",
    "color": "blue",
    "tires": [{
        "make": "Mishlen",
        "size": 185
    }, {
        "make": "Mishlen",
        "size": 210
    }]
}

Result :

{
    "make": "Toyota",
    "color": "blue",
    "tires": [{
        "make": "Mishlen",
        "size": 185
    }]
}

Ref : $addFields , $filter

Upvotes: 1

Related Questions