hari prasanth
hari prasanth

Reputation: 746

How to use $elemMatch query in mongodb

I tried to filter the data using $elemmatch but it's not correctly working.
My Scenario

Prod Table

[
  {
    id:1.
    product:[
     {
       id:1,
       name:true
     },
     {
       id:2,
       name:true
     },
     {
      id:3,
      name:false
     }
   ]
  }
]  

Query

db.Prod.find(
    {"product.name": true}, 
    {_id: 0, product: {$elemMatch: {name: true}}});

I got Output

[
 {
   id:1.
   product:[
     {
       id:1,
       name:true
     }
  ]
 }
]

Excepted Output

[
 {
   id:1.
   product:[
    {
      id:1,
      name:true
    },
    {
     id:2,
     name:true
    }
   ]
  }
]  

How to achieve this Scenario and I referred this Link Retrieve only the queried element in an object array in MongoDB collection and I tried all the answers in this link mentioned. but Still it's not working can give an example query.

Upvotes: 0

Views: 381

Answers (1)

matthPen
matthPen

Reputation: 4343

Hmm, you probably didn't try the aggregation provided in referenced link, 'cause it perfectly works.

db.collection.aggregate([
  {
    $match: {
      "product.name": true
    }
  },
  {
    $project: {
      product: {
        $filter: {
          input: "$product",
          as: "prod",
          cond: {
            $eq: [
              "$$prod.name",
              true
            ]
          }
        }
      }
    }
  }
])

Will output :

[
  {
    "_id": 1,
    "product": [
      {
        "id": 1,
        "name": true
      },
      {
        "id": 2,
        "name": true
      }
    ]
  }
]

Here's the example.

EDIT : From the doc :

Usage Considerations

Both the $ operator and the $elemMatch operator project the first matching element from an array based on a condition.

Considering this, you cannot achieve what you need with a find query, but only with an aggregation query.

Upvotes: 1

Related Questions