1
votes

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"}]}
]
  1. How can we get the name field of all the documents having only country: "Germany" in locations subdocument?

    Example: Using the sample collection items above, then executing the above query should return [{name: "D"}]

  2. How can we get the name field of all the documents with locations subdocument not having country: France or country: "Germany" (or both) as an element?

    Example: Using the sample collection items above, 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.

1
1-db.test.find({"locations": [{ "country" : "Germany" }]}) - Disposer
That will only work if we assume locations will only contain one key/value country: "Germany". If there are other key/value pairs, it will not work. - tria

1 Answers

1
votes

How can we get the name field of all the documents having only country: "Germany" in locations subdocument?

The $size operator will come in handy for this:

db.foo.find({locations:{$size:1}, "locations.country":"Germany"})

How can we get the name field of all the documents with locations subdocument not having country: France or country: "Germany" (or both) as an element?

The $nin operator will come in handy for this:

db.foo.find({"locations.country":{$nin:["Germany", "France"]}})