如何使用 Mongo 返回具有已篩選子文件的文件?


為此,請在 MongoDB 中使用 $project。在其內部,使用 $filter。讓我們建立一個帶有文件的集合 -

> db.demo457.insertOne(
... {
...    _id: 101,
...    details: [
...       { ProductName:"Product-1" , ProductPrice:90 },
...       { ProductName:"Product-2" , ProductPrice:190 }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
>
> db.demo457.insertOne(
... {
...    _id: 102,
...    details: [
...       { ProductName:"Product-3" , ProductPrice:150},
...       { ProductName:"Product-4" , ProductPrice:360 }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 102 }

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

> db.demo457.find();

這將產生以下輸出 −

{ "_id" : 101, "details" : [ { "ProductName" : "Product-1", "ProductPrice" : 90 }, { "ProductName"
: "Product-2", "ProductPrice" : 190 } ] }
{ "_id" : 102, "details" : [ { "ProductName" : "Product-3", "ProductPrice" : 150 }, {
"ProductName" : "Product-4", "ProductPrice" : 360 } ] }

以下是使用 MongoDB 返回具有已篩選子文件的文件的查詢 −

> db.demo457.aggregate([
... {
...    $project: {
...       details: {
...          $filter: {
...             input: "$details",
...             as: "output",
...             cond: { $gte: [ "$$output.ProductPrice", 170 ] }
...          }
...       }
...    }
... }
... ])

這將產生以下輸出 −

{ "_id" : 101, "details" : [ { "ProductName" : "Product-2", "ProductPrice" : 190 } ] }
{ "_id" : 102, "details" : [ { "ProductName" : "Product-4", "ProductPrice" : 360 } ] }

更新於: 11-5-2020

113 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.