在 MongoDB 中使用 ObjectId 在 findOne() 下获取特定记录?
让我们首先使用文档创建一个集合 −
> db.findOneWorkingDemo.insertOne({"ClientId":1,"ClientName":"Larry","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c1716d78f205348bc64d") } > db.findOneWorkingDemo.insertOne({"ClientId":2,"ClientName":"Chris","ClientAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c17d6d78f205348bc64e") } > db.findOneWorkingDemo.insertOne({"ClientId":3,"ClientName":"Robert","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7c1896d78f205348bc64f") }
以下查询用于使用 find() 方法显示集合中的所有文档 −
> db.findOneWorkingDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd7c1716d78f205348bc64d"), "ClientId" : 1, "ClientName" : "Larry", "ClientAge" : 26 } { "_id" : ObjectId("5cd7c17d6d78f205348bc64e"), "ClientId" : 2, "ClientName" : "Chris", "ClientAge" : 28 } { "_id" : ObjectId("5cd7c1896d78f205348bc64f"), "ClientId" : 3, "ClientName" : "Robert", "ClientAge" : 34 }
以下查询使用 ObjectId 实现 findOne() −
> db.findOneWorkingDemo.findOne({"_id":ObjectId("5cd7c17d6d78f205348bc64e")});
这将产生以下输出 −
{ "_id" : ObjectId("5cd7c17d6d78f205348bc64e"), "ClientId" : 2, "ClientName" : "Chris", "ClientAge" : 28 }
广告