如何在 MongoDB 嵌入式文档中查找某个元素?
为了查找某个元素,在 MongoDB 中使用 $project。让我们创建一个文档集合 -
> db.demo744.insertOne(
... {
... studentInformation:
... [
... {
... studentName:"Robert",
... grade:"A"
... },
... {
... studentName:"Bob",
... grade:"C"
... },
... {
... studentName:"John",
... grade:"B"
... },
... {
... studentName:"Sam",
... grade:"A"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ead928a57bb72a10bcf0684")
}使用 find() 方法从集合中显示所有文档 -
> db.demo744.find();
这将生成以下输出 -
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : [ { "studentName" : "Robert", "grade" : "A" }, { "studentName" : "Bob", "grade" : "C" }, { "studentName" : "John", "grade" : "B" }, { "studentName" : "Sam", "grade" : "A" } ] }以下是查询,用于在嵌入式文档中查找某个元素 -
> db.demo744.aggregate(
... { $unwind: '$studentInformation' },
... { $match: {'studentInformation.grade':"A"}},
... { $project: {"studentInformation.studentName": 1}}
... )这将生成以下输出 -
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Robert" } }
{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Sam" } }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP