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