0

A test collection has one document.

db.test.insert({
     "_id" : ObjectId("5922bd14ff3ee9313229ac18"),
     "O" : [
             {
                     "A" : "Field_1",
                     "B" : "Unknown"
             },
             {
                     "A" : "Field_2",
                     "B" : "Unknown_Location"
             }
     ]

})

I want this entry to return only if both the A and the B filter's match in one of the documents.

For example, TEST CASE 1:

db.test.find({"O.A" : "Field_2", "O.B" : "Unknown_Location"}).count()
1
db.test.find({"O.A" : "Field_1", "O.B" : "Unknown"}).count()
1

TEST CASE 2 But the following query also returns this entry, for which causes problems:

db.test.find({"O.A" : "Field_1", "O.B" : "Unknown_Location"}).count()
1

Help is sincerely appreciated.

This question is different from Retrieve only the queried element in an object array in MongoDB collection In that question, the question was to retrieve a part and was solved by projecting a part of matched document.

My Problem is that the match in the TEST CASE 2 is unwanted and I need to change my query accordingly.

MonsieurBeilto
  • 878
  • 1
  • 11
  • 18
  • @neil-lunn Have explained why the question is different – MonsieurBeilto May 31 '17 at 02:12
  • How? `{ "O": { "$elemMatch": { "A": "Field_1", "B": "Unknown_Location" } } }` will not match any **document** since there is no array element matching those conditions. You also nee `$elemMatch` otherwise the statement matches *"any position in the array"*, so you use it for the combination of keys. If you are asking *"How to retrieve just the matched elements ( in plural )"* then there are aggregation examples showing `$filter` there. Same question. If you really think differently, then explain your difference in your question. But I think you should try using the correct query expressions. – Neil Lunn May 31 '17 at 02:13
  • You are right, db.test.find( { "O": { $elemMatch: { A: "Field_1", B: "Unknown_Location" } } } ) does solve the issue. Does $elemMatch use indexes, and can it be optimized? Or does it need to scan all? – MonsieurBeilto May 31 '17 at 02:17
  • Yes it can use an index. You can read the documentation [`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/query/elemMatch/) along with various similar documentation links included in the linked question. – Neil Lunn May 31 '17 at 02:28

0 Answers0