如何在陣列中使用多鍵索引提高 MongoDB 查詢?


為此,使用 $elemMatch,用於查詢巢狀物件。我們建立一個包含文件的集合 -

> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:1,
...          Name:"Chris"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea87bbc41e36cc3caebf")
}
> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:2,
...          Name:"David"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea87bbc41e36cc3caec0")
}
> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:3,
...          Name:"Bob"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea88bbc41e36cc3caec1")
}

在集合中顯示所有文件,利用 find() 方法 -

> db.demo444.find();

這將生成以下輸出 -

{ "_id" : ObjectId("5e78ea87bbc41e36cc3caebf"), "Information" : [ { "id" : 1, "Name" : "Chris" } ] }
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }
{ "_id" : ObjectId("5e78ea88bbc41e36cc3caec1"), "Information" : [ { "id" : 3, "Name" : "Bob" } ] }

以下是如何使用多鍵索引在陣列中改進查詢 -

> db.demo444.find({
...    "Information":{
...       $elemMatch:{
...          id:2,
...          Name:"David"
...       }
...    }
... })

這將生成以下輸出 -

{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }

更新日期:06-4-2020

136 瀏覽

開啟你的職業生涯

透過完成課程認證

開始
廣告
© . All rights reserved.