使用对象作为密钥来在 MongoDB 中查找值


要查找值,请在 MongoDB 中使用 find()。在此之下,使用点符号。让我们创建一个包含文档的集合 −

> db.demo361.insertOne({"details":{"FirstName":"Chris","LastName":"Brown"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a61f54a481fef8ec7a19")
}
> db.demo361.insertOne({"details":{"FirstName":"David","LastName":"Miller"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a62854a481fef8ec7a1a")
}
> db.demo361.insertOne({"details":{"FirstName":"John","LastName":"Doe"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a63654a481fef8ec7a1b")
}

使用 find() 方法从集合中显示所有文档 −

> db.demo361.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e56a61f54a481fef8ec7a19"), "details" : { "FirstName" : "Chris", "LastName" : "Brown" } }
{ "_id" : ObjectId("5e56a62854a481fef8ec7a1a"), "details" : { "FirstName" : "David", "LastName" : "Miller" } }
{ "_id" : ObjectId("5e56a63654a481fef8ec7a1b"), "details" : { "FirstName" : "John", "LastName" : "Doe" } }

以下是使用对象作为密钥来查找值的操作: −

> db.demo361.find({},{"details.LastName":1});

这将产生以下输出 −

{ "_id" : ObjectId("5e56a61f54a481fef8ec7a19"), "details" : { "LastName" : "Brown" } }
{ "_id" : ObjectId("5e56a62854a481fef8ec7a1a"), "details" : { "LastName" : "Miller" } }
{ "_id" : ObjectId("5e56a63654a481fef8ec7a1b"), "details" : { "LastName" : "Doe" } }

更新于:02-Apr-2020

1K+ 次浏览

Kickstart Your Career

通过完成课程获得认证

开始
广告