要查询MongoDB中的嵌入式文档,请使用aggregate()。让我们创建一个包含文档的集合-
> db.demo705.insertOne(
... {
... _id:101,
... "Information":
... [
... {
... "StudentName":"Chris",
... "StudentAge":21
... },
... {
... "StudentName":"David",
... "StudentAge":23
... },
... {
... "StudentName":"Bob",
... "StudentAge":20
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo705.find();
这将产生以下输出-
{ "_id" : 101, "Information" : [ { "StudentName" : "Chris", "StudentAge" : 21 }, { "StudentName" : "David", "StudentAge" : 23 }, { "StudentName" : "Bob", "StudentAge" : 20 } ] }
以下是如何在MongoDB中查询嵌入式文档-
> db.demo705.aggregate(
... { $unwind: '$Information' },
... { $match: {'Information.StudentAge': {$gte: 21}}},
... { $project: {Information: 1}}
... )
这将产生以下输出-
{ "_id" : 101, "Information" : { "StudentName" : "Chris", "StudentAge" : 21 } }
{ "_id" : 101, "Information" : { "StudentName" : "David", "StudentAge" : 23 } }