如何使用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 } ] }热门推荐
10 国庆简短幽默祝福语
11 下雨开工吉祥祝福语简短
12 老师开工仪式祝福语简短
13 大寿爸爸祝福语简短英文
14 祝福语签名简短大全女生
15 俄语祝福语贺卡文案简短
16 教练生日祝福语 简短独特
17 美丽晚霞祝福语简短句
18 比赛结束花束祝福语简短