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:
{"input.name":{$all:["IAA1","IAA2","IAA3"]}}
This works fine and returns both documents, but this:
{"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.
_id?_idof the second doc.$allis equivalent to$andso above query in$andas{"$and":[{"input.name":"IAA1"},{"input.name":"IAA2"}]}this match both documents because"IAA1","IAA2"contains in both documents. To find exact macth you should useaggregation.