如何在 MongoDB 中过滤对象中的某些字段并获取特定主题名称的值?
mongodbdatabasebig data analytics更新于 2026/2/11 10:07:17
要进行过滤和获取,请使用投影以及 MongoDB $filter 和 $match。让我们创建一个包含文档 − 的集合。
> db.demo507.insertOne(
... {
...
... "Information":
... [
... {"Name":"John","SubjectName":"MySQL"},
... {"Name":"Bob","SubjectName":"MongoDB"},
... {"Name":"Chris","SubjectName":"MySQL"},
... {"Name":"David","SubjectName":"C++"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8836d3987b6e0e9d18f577")
}
借助 find() 方法显示集合中的所有文档 −
> db.demo507.find().pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5e8836d3987b6e0e9d18f577"),
"Information" : [
{
"Name" : "John",
"SubjectName" : "MySQL"
},
{
"Name" : "Bob",
"SubjectName" : "MongoDB"
},
{
"Name" : "Chris",
"SubjectName" : "MySQL"
},
{
"Name" : "David",
"SubjectName" : "C++"
}
]
}
以下是过滤对象中某些字段的查询 −
> db.demo507.aggregate([
... {$match: {"Information.SubjectName" : "MySQL" } },
... {$project: {
... _id:0,
... Information: {
... $filter: {
... input: '$Information',
... as: 'result',
... cond: {$eq: ['$$result.SubjectName', 'MySQL']}
... }
... }
... }
... },{$project: {Information: { SubjectName:1}}}
... ]);
这将产生以下输出 −
{ "Information" : [ { "SubjectName" : "MySQL" }, { "SubjectName" : "MySQL" } ] }

