MongoDB查询将匹配的键添加到查询后的列表?
为此,请aggregate()
在MongoDB中使用。让我们创建一个包含文档的集合-
> db.demo334.insertOne({ ... "Name": "Chris", ... "Age": 21, ... "details": [{ ... "Subject": "MySQL", ... "Score": 78 ... }, { ... "Subject": "MongoDB", ... "Score": 45 ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e52241bf8647eb59e562090") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo334.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e52241bf8647eb59e562090"), "Name" : "Chris", "Age" : 21, "details" : [ { "Subject" : "MySQL", "Score" : 78 }, { "Subject" : "MongoDB", "Score" : 45 } ] }
以下是在查询后将匹配的键添加到列表的查询-
> db.demo334.aggregate([ ... { $addFields: { ... details: {$filter: { ... input: '$details', ... as: 'out', ... cond: {$gte: ['$$out.Score',70 ]} ... }} ... }} ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e52241bf8647eb59e562090"), "Name" : "Chris", "Age" : 21, "details" : [ { "Subject" : "MySQL", "Score" : 78 } ] }