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


要根据特定属性显示对象列表,在 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 } ] } }

更新于:11-May-2020

277 次浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.