2

I have a collection in MongoDB that looks like this:

{
 "_id" : 1,
 "parent" : 1,
 "input" : [
     {
       "name" : "IAA1",
       "value" : "IAA1 Value3",
       "displayOrder" : 1
     },
     {
       "name" : "IAA2",
       "type" : "IAA2 Value4",
       "displayOrder" : 2
     }]
}

{
 "_id" : 2,
 "parent" : 1,
 "input" : [
    {
      "name" : "IAA1",
      "value" : "IAA1 Value3",
      "displayOrder" : 1
    },
    {
      "name" : "IAA2",
      "type" : "IAA2 Value4",
      "displayOrder" : 2
    },
    {
       "name" : "IAA3",
       "type" : "IAA2 Value4",
       "displayOrder" : 2
    } ]
}

What I need to do is, find only those documents that have all array elements that match the value of the name. For example:

  1. {"input.name":{$all:["IAA1","IAA2","IAA3"]}}

This works fine and returns both documents, but this:

  1. {"input.name":{$all:["IAA1","IAA2"]}}

Returns both documents as well. My requirements is that the 2nd query should only return the first document and not the second as it has an extra element with name:"IAA3".

The order of the elements in the array is not fixed I need to generate the query dynamically based on parent Id and what columns should be present.

3
  • How can your documents have the same _id ? Commented Apr 30, 2015 at 6:16
  • My bad, I have updated the _id of the second doc. Commented Apr 30, 2015 at 6:20
  • $all is equivalent to $and so above query in $and as {"$and":[{"input.name":"IAA1"},{"input.name":"IAA2"}]} this match both documents because "IAA1","IAA2" contains in both documents. To find exact macth you should use aggregation . Commented Apr 30, 2015 at 6:27

2 Answers 2

2

You need to use combination of $size and $all operator to get desired result. size must be the number of parameters that you are using in $all. Here you must check size of input array to number of params in $all so that it will search given parameters ($all) only in those input array which size matches to number of params.

e.g. In sample Json you are using 2 params in $all so you must give $size of input as 2. In this case query will search only those input whose size is 2.

The query will be like -

db.collection.find({
"input.name": {
    $all: ["IAA1", "IAA2"]
},
"input": {
    $size: 2 // This is the number of param you pass in $all
}
}).pretty()
Sign up to request clarification or add additional context in comments.

1 Comment

@Phoenix is it helpful to you??
0

In order to have exact match, you should query just by the elements in the array. For eg:

{"input.name":["IAA1", "IAA2"]}

Refer here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.