如何使用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 } ] } }