使用 MongoDB 的_id 查询

时间:2021-08-17 12:26:56

MongoDB 默认在插入数据时,生成一个主键_id,那么怎么使用_id来查询数据?

查询全部

> db.foo.find()
{ "_id" : ObjectId("544a3dd5d4646f0c8c904964"), "a" : 3 }
{ "_id" : ObjectId("544a3ddad4646f0c8c904965"), "a" : 4 }
{ "_id" : ObjectId("544a3dd0d4646f0c8c904963"), "a" : "2.3", "name" : "zhangsan" }
{ "_id" : ObjectId("544a3dc0d4646f0c8c904962"), "a" : 7, "name" : "zhangsan2" }

使用_id来查询数据:
> db.foo.find({"_id" : ObjectId("544a3dc0d4646f0c8c904962")})
{ "_id" : ObjectId("544a3dc0d4646f0c8c904962"), "a" : 7, "name" : "zhangsan2" }

http://www.runoob.com/mongodb/mongodb-tutorial.html

http://www.mongoing.com/