如何在 MongoDB 中搜索一个集合,以找到其中一个文档中的嵌套值?
为此,在 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" } }
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP