Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo query with projection

In mongo how to return all the match dict element from a list if the condition is match.

here is my data:

    {"packages": [
       {"package_name" : "abc", "installed_date" : "2016-08-03"},
       {"package_name" : "def", "installed_date" : "2016-08-04"},
       {"package_name" : "ghi", "installed_date" : "2016-08-03"},
       ]
    }

How should I query to get all the dictionary which match {"installed_date" : "2016-08-03"}

I tried:

db.resource.find({packages: {"$elemMatch": {installed_date: "2016-08-03"}}})

But this give me all the array element. I would like to get the dict element which match {installed_date: "2016-08-03"}

Thanks

like image 769
James Avatar asked Apr 22 '26 17:04

James


1 Answers

Try mongo aggregation:

db.resource.aggregate([
  {'$match':{'packages.installed_date':'2016-08-03'}}, 
  {'$unwind':'$packages'}, 
  {'$match':{'packages.installed_date':'2016-08-03'}}, 
  {'$group':{'_id':'$_id', 'packages':{'$push':'$packages'}}}
])
like image 154
Gaurav Kumar Avatar answered Apr 25 '26 09:04

Gaurav Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!