如何在 MongoDB 中搜索集合并查找其文档中的嵌套值?
mongodbdatabasebig data analytics更新于 2026/1/10 12:52:17
为此,请在 find() 中使用双下划线 ( __)。首先,我们创建一个包含文档的集合 −
> db.nestedDemo.insertOne({"Information":{"__StudentName":"John Smith"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f39125ddae1f53b621f0")
}
> db.nestedDemo.insertOne({"Information":{"__StudentName":"John Doe"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f39e25ddae1f53b621f1")
}
> db.nestedDemo.insertOne({"Information":{"__StudentName":"Chris Brown"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f3a625ddae1f53b621f2")
}
以下是使用 find() 方法显示集合中的所有文档的查询 −
> db.nestedDemo.find().pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5e06f39125ddae1f53b621f0"),
"Information" : {
"__StudentName" : "John Smith"
}
}
{
"_id" : ObjectId("5e06f39e25ddae1f53b621f1"),
"Information" : {
"__StudentName" : "John Doe"
}
}
{
"_id" : ObjectId("5e06f3a625ddae1f53b621f2"),
"Information" : {
"__StudentName" : "Chris Brown"
}
}
这是在 MongoDB 中搜索集合以在其文档之一中查找嵌套值的查询 −
> db.nestedDemo.find({"Information.__StudentName":"John Doe"});
这将产生以下输出 −
{ "_id" : ObjectId("5e06f39e25ddae1f53b621f1"), "Information" : { "__StudentName" : "John Doe" } }

