Reputation: 33
I have a Collection in each document is an array field and I want to search it for the occurrence of elements that are in another array and output the indexes of elements that are found as an array.
For example:
I have a document with foo field,
{
foo = [1,4,3,6,6],
foo = [1,5,7,5,8],
foo = [2,4,3,1,6],
foo = [1,4,9,6,7]
}
and an array which contains the elements to be searched
bar = [3,6]
I want the output to be
{output = [2,3]}
{output = [-1,-1]}
{output = [2,4]}
{output = [-1,3]}
I have tried using aggregation pipeline and map function with $indexOfArray but can't seem to make it work.
Upvotes: 2
Views: 166
Reputation: 75914
You can use $map
expression.
db.collection.aggregate([
{"$project":{
"output":{
"$map":{
"input":[3,6],
"in":{"$indexOfArray":["$foo","$$this"]}
}
}
}}
])
Upvotes: 1