如何在查詢文件時阻止 MongoDB 返回物件 ID?
如要阻止 MongoDB 在查詢文件時返回物件 ID,你需要將_id 設為 0。我們先建立一個帶有文件的集合
> db.preventObjectIdDemo.insertOne(
... {
...
... "StudentName" : "Chris",
... "StudentDetails" : [
... {
... "StudentTotalScore" : 540,
... "StudentCountryName" : "US"
... },
... {
... "StudentTotalScore" : 489,
... "StudentCountryName" : "UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca20a9c66324ffac2a7dc63")
}以下是使用 find() 方法從集合中顯示所有文件的查詢
> db.preventObjectIdDemo.find().pretty();
這將產生以下輸出
{
"_id" : ObjectId("5ca20a9c66324ffac2a7dc63"),
"StudentName" : "Chris",
"StudentDetails" : [
{
"StudentTotalScore" : 540,
"StudentCountryName" : "US"
},
{
"StudentTotalScore" : 489,
"StudentCountryName" : "UK"
}
]
}以下是阻止 MongoDB 在查詢文件時返回物件 ID 的查詢
> db.preventObjectIdDemo.find({ _id: ObjectId("5ca20a9c66324ffac2a7dc63")},
{StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty();以下是輸出,其中看不到 ObjectID
{
"StudentName" : "Chris",
"StudentDetails" : [
{
"StudentTotalScore" : 540,
"StudentCountryName" : "US"
}
]
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP