MongoDB - 查询嵌入式文档?
要在 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 } }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP