在 MongoDB 文档中查找填充的嵌套数组,并重塑文档结果
我们首先使用文档创建集合 -
> db.demo187.insertOne( ... { ... "_id" : "101", ... "Details" : [ ... { "Subject" : "MongoDB" }, ... { "Subject" : "MySQL" } ... ] ... } ...); { "acknowledged" : true, "insertedId" : "101" } > db.demo187.insertOne( ... { ... "_id" : "102", ... "Details" : [ ... { } ... ] ... } ...); { "acknowledged" : true, "insertedId" : "102" } > db.demo187.insertOne( ... { ... "_id" : "103", ... "Details" : [ ... { "Subject" : "MongoDB" }, ... { "Subject" : "MySQL" } ... ] ... } ...); { "acknowledged" : true, "insertedId" : "103" }
借助 find() 方法显示集合中的所有文档 -
> db.demo187.find();
这将产生以下输出 -
{ "_id" : "101", "Details" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] } { "_id" : "102", "Details" : [ { } ] } { "_id" : "103", "Details" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }
以下是查找填充嵌套数组的 MongoDB 文档的查询 -
> db.demo187.aggregate([ ... ... {$unwind: '$Details'}, ... ... {$project: {Subject: '$Details.Subject'}}, ... ... {$match: {Subject: {$exists: true}}} ... ])
这将产生以下输出 -
{ "_id" : "101", "Subject" : "MongoDB" } { "_id" : "101", "Subject" : "MySQL" } { "_id" : "103", "Subject" : "MongoDB" } { "_id" : "103", "Subject" : "MySQL" }
广告