在 MongoDB 中查找具有“ObjectId”的文档?
若要在 MongoDB 中查找具有“ObjectId”的文档,请使用以下语法:
db.yourCollectionName.find({"_id":ObjectId("yourObjectIdValue")}).pretty();为了理解上述语法,让我们创建一个带有文档的集合。创建含有文档的集合的查询如下所示:
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4384afe5c1d2279d69b")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Mike","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4444afe5c1d2279d69c")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Carol","UserAge":26,"UserHobby":["Learning","Photography"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e4704afe5c1d2279d69d")
}使用“find()”方法从集合中显示所有文档。查询如下:
> db.findDocumentWithObjectIdDemo.find().pretty();
输出如下:
{ "_id" : ObjectId("5c90e4384afe5c1d2279d69b"), "UserName" : "Larry" }
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
}
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
}案例 1 :这是在 MongoDB 中查找具有 “ObjectId” 的文档的查询。
> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty();输出如下:
{
"_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName" : "Carol",
"UserAge" : 26,
"UserHobby" : [
"Learning",
"Photography"
]
}案例 2 :这是在 MongoDB 中查找具有“ObjectId”的另一个文档的查询。
查询如下:
> db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty();输出如下:
{
"_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName" : "Mike",
"UserAge" : 23
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP