在子文件中作為陣列一部分,匹配 _id 的 MongoDB 查詢?


讓我們建立一個包含文件的集合 -

> db.demo568.insertOne({ _id: 101, details: [ {id : 101 }, { id:103 } ] });
{ "acknowledged" : true, "insertedId" : 101 }

使用 find() 方法顯示集合中的所有文件 -

> db.demo568.find();

這會生成以下輸出 -

{ "_id" : 101, "details" : [ { "id" : 101 }, { "id" : 103 } ] }
Following is the query to create second collection:
> db.demo569.insertOne({ _id: 101, details: "John" })
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo569.insertOne({ _id: 102, details: "Chris" })
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo569.insertOne({ _id: 103, details: "David" })
{ "acknowledged" : true, "insertedId" : 103 }

使用 find() 方法顯示集合中的所有文件 -

> db.demo569.find();

這會生成以下輸出 -

{ "_id" : 101, "details" : "John" }
{ "_id" : 102, "details" : "Chris" }
{ "_id" : 103, "details" : "David" }

以下是匹配 _id 在子文件中作為陣列一部分的文件的查詢 -

> db.demo569.find({ '_id': { '$in': db.demo568.distinct('details.id', {'_id': 101}) }})

這會生成以下輸出 -

{ "_id" : 101, "details" : "John" }
{ "_id" : 103, "details" : "David" }

更新於:2020 年 5 月 14 日

160 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.