要过滤特定值,请在MongoDB中使用$filter。让我们创建一个包含文档的集合-
> db.demo751.insertOne( ... { ... _id: 101, ... details: [ ... { Name: "Robert", id:110,Age:21}, ... { Name: "Rae", id:110,Age:22}, ... {Name: "Ralph", id:116,Age:23} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo751.find().pretty();
这将产生以下输出-
{ "_id" : 101, "details" : [ { "Name" : "Robert", "id" : 110, "Age" : 21 }, { "Name" : "Rae", "id" : 110, "Age" : 22 }, { "Name" : "Ralph", "id" : 116, "Age" : 23 } ] }
以下是要过滤的查询-
> db.demo751.aggregate([ ... { ... $addFields: { ... details: { ... $let: { ... vars: { ... filtered: { $filter: { input: "$details", as: "out", cond: { $eq: [ "$$out.id", 110 ] } } } ... }, ... in: { $slice: [ "$$filtered", -1 ] } ... } ... } ... } ... } ... ])
这将产生以下输出-
{ "_id" : 101, "details" : [ { "Name" : "Rae", "id" : 110, "Age" : 22 } ] }