Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to search an array for values present in another array and output the indexes of values found into a new array in MongoDB?
For this, use $indexOfArray. Let us first create a collection with documents −
> db.demo381.insertOne({"Values":[10,40,60,30,60]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5b59f72ae06a1609a00b15")
}
> db.demo381.insertOne({"Values":[100,500,700,500,800]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5b59f72ae06a1609a00b16")
}
> db.demo381.insertOne({"Values":[20,40,30,10,60]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5b59f72ae06a1609a00b17")
}
Display all documents from a collection with the help of find() method −
> db.demo381.find();
This will produce the following output −
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b15"), "Values" : [ 10, 40, 60, 30, 60 ] }
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b16"), "Values" : [ 100, 500, 700, 500, 800 ] }
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b17"), "Values" : [ 20, 40, 30, 10, 60 ] }
Following is the query to search an array for values present in another array and output the indexes of values found into a new array in MongoDB −
> db.demo381.aggregate([
... {"$project":{
... "Result":{
... "$map":{
... "input":[10,40],
... "in":{"$indexOfArray":["$Values","$$this"]}
... }
... }
... }}
... ])
This will produce the following output −
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b15"), "Result" : [ 0, 1 ] }
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b16"), "Result" : [ -1, -1 ] }
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b17"), "Result" : [ 3, 1 ] }Advertisements