为此,请在中使用双下划线(__)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" } }