在 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
}

更新日期:2019 年 7 月 30 日

272 個瀏覽量

開啟您的 職業 生涯

完成課程來獲得認證

開始吧
廣告
© . All rights reserved.