In MongoDB, suppose we have a collection items with the following sample data:
[
{name: "A", locations: [{country: "USA"}, {country: "Germany"}]},
{name: "B", locations: [{country: "USA"}],
{name: "C", locations: [{country: "France"}, {country: "Germany"}]},
{name: "D", locations: [{country: "Germany"}]},
{name: "E", locations: [{country: "USA"}, {country: "UK"}]}
]
How can we get the
namefield of all the documents having onlycountry: "Germany"inlocationssubdocument?Example: Using the sample collection
itemsabove, then executing the above query should return[{name: "D"}]How can we get the
namefield of all the documents withlocationssubdocument not havingcountry: Franceorcountry: "Germany"(or both) as an element?Example: Using the sample collection
itemsabove, then executing the above query should return[{name: "B"}, {name: "E"}]
I've read the documentation, and tried many things, and I ended up handling it using two steps. Querying with the most specific query I came up with, then filtering unneeded documents through looping over the documents (array) programmatically. I would prefer to know if either of the previous queries could be achieved directly by a single query.
Note: The documents/queries are only samples, and the documents/queries I am dealing with are different.
locationswill only contain one key/valuecountry: "Germany". If there are other key/value pairs, it will not work. - tria