如何在 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 ] }

更新時間: 02-Apr-2020

543 瀏覽量

開啟您的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.