如何在一个数组中搜索另一个数组中存在的值,并将找到的值的索引输出到MongoDB中的新数组中?
为此,请使用$indexOfArray。首先让我们创建一个包含文档的集合-
> 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")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo381.find();
这将产生以下输出-
{ "_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 ] }以下是查询以在数组中查找另一个数组中存在的值,并将找到的值的索引输出到MongoDB中的新数组中的查询-
> db.demo381.aggregate([
... {"$project":{
... "Result":{
... "$map":{
... "input":[10,40],
... "in":{"$indexOfArray":["$Values","$$this"]}
... }
... }
... }}
... ])这将产生以下输出-
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b15"), "Result" : [ 0, 1 ] }
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b16"), "Result" : [ -1, -1 ] }
{ "_id" : ObjectId("5e5b59f72ae06a1609a00b17"), "Result" : [ 3, 1 ] }