0

I am trying to build a mongo query (below) but not getting any results back, my Mongo collection fields (shown in picture). I am trying to elemMatch on Packaes.Tier = Gold, so expecting to get back the Packages array with one element for the Gold Tier.

db.getCollection('FacilityProfiles').find({$and : [
    {"Packages" : {$elemMatch : {"Packages.Tier" : "Gold"}}}
    ]},
    {"Packages" : 1}
)

I also tried these queries but it returned both elements:

db.getCollection('FacilityProfiles').find({$and : [
    {"Packages.StartDate" : {$lte : new Date}}
    ]},
    {"Packages" : 1}
)

db.getCollection('FacilityProfiles').find({$and : [
   {"Packages.StartDate" : {$lte : new Date}},
   {"Packages.EndDate" : {$gte : new Date}}
   ]},
   {"Packages" : 1}
)

db.getCollection('FacilityProfiles').find({$and : [
    {"ProfileLanguage" : "EN"},{"spctr_FacilityId" : "000018211"},
    {"Packages.StartDate" : {$lte : new Date},"Packages.EndDate" : {$gte : new Date}}    
    ]},
    {"Packages" : 1}
)

So based on my Mongo collection values is possible to build a query to get only the gold package element from the Packages array I am trying to get only the Package element where the current date is between start and end date essentially currentdate between StartDate and EndDate

my mongo collection is: enter image description here

UPdate: I tried $elemMatch but still get back both elements in the array

db.getCollection('FacilityProfiles').find(
    {"Packages" : { $elemMatch : { "PackageCode" : "G",  "StartDate" : {$lte : new Date()}, "EndDate" : {$gte : new Date()} }}}
)
Jawahar
  • 53
  • 4
  • 12
  • You actually started with the correct operator and then it all went wrong. Read the [`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/query/elemMatch/) documentation again and also reference [Specify Multiple Conditions for Array of Documents](https://docs.mongodb.com/manual/tutorial/query-array-of-documents/) in the documentation as well. Both actually give the same example of a "between" for an array element. – Neil Lunn Nov 22 '18 at 20:15
  • Thanks for your suggestions. I did try with $elemMatch but i still get both elements in the array returned: db.getCollection('FacilityProfiles').find( {"Packages" : { $elemMatch : { "PackageCode" : "G", "StartDate" : {$lte : new Date()}, "EndDate" : {$gte : new Date()} }}} ) – Jawahar Nov 22 '18 at 21:24
  • That's actually expected. "Filtering Arrays" is a different thing to "Querying a Document". It also has of course an existing answer and is a very common question. – Neil Lunn Nov 22 '18 at 21:27

0 Answers0