如何使用 MongoDB 根据特定属性显示对象列表?

mongodbdatabasebig data analytics更新于 2026/2/11 17:07:17

要根据特定属性显示对象列表,请在 find() 中使用点符号。让我们创建一个包含文档的集合 −

> db.demo455.insertOne({"Information":{"Student":[{"Name":"Chris","Age":22}]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7e1876dbcb9adb296c95c5")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"David","Age":21}]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7e1883dbcb9adb296c95c6")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"Bob","Age":24}]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7e188adbcb9adb296c95c7")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"Robert","Age":21}]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7e18bcdbcb9adb296c95c8")
}

借助 find() 方法显示集合中的所有文档 −

> db.demo455.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e7e1876dbcb9adb296c95c5"), "Information" : { "Student" : [ { "Name" :
"Chris", "Age" : 22 } ] } }
{ "_id" : ObjectId("5e7e1883dbcb9adb296c95c6"), "Information" : { "Student" : [ { "Name" :
"David", "Age" : 21 } ] } }
{ "_id" : ObjectId("5e7e188adbcb9adb296c95c7"), "Information" : { "Student" : [ { "Name" :
"Bob", "Age" : 24 } ] } }
{ "_id" : ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information" : { "Student" : [ { "Name" :
"Robert", "Age" : 21 } ] } }

以下查询用于显示基于特定属性的对象列表 −

> db.demo455.find({"Information.Student.Age":21});

这将产生以下输出 −

{ "_id" : ObjectId("5e7e1883dbcb9adb296c95c6"), "Information" : { "Student" : [ { "Name" :
"David", "Age" : 21 } ] } }
{ "_id" : ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information" : { "Student" : [ { "Name" :
"Robert", "Age" : 21 } ] } }

相关文章