robert popi
robert popi

Reputation: 77

how to filter the fields of a document within another document in mongodb?

My document is the following

{

 "name":"Name1",
  "status":"active",
  "points":[
   {
      "lag":"final"
   },
   {
      "lag":"final"
   }
   
  ]
},
{

 "name":"Name2",
 "status":"active",
  "points":[
   {
      "lag":"final"
   },
   {
      "lag":""
   }
   
  ]
}

I need to get all the documents that have some value in the lag field, for this example should get two document, I tried with this query, but it only returns me when all points have full lag

{ "points.lag":{$not:{ $eq:"" }},status:{$in:['active']}}

Upvotes: 1

Views: 402

Answers (1)

Gibbs
Gibbs

Reputation: 22974

Play

You need to use elemMatch to check whether atleast one element matches the condition.

db.collection.find({
  "points": {
    "$elemMatch": {
      "lag": {
        $ne: null
      }
    }
  }
})

Upvotes: 1

Related Questions