MongoDB 中的專案欄位


若要投影 MongoDB 中的欄位,請使用 $project。我們使用文件建立一個集合 −

> db.demo439.insertOne(
...    {
...       "Name" : "Chris",
...       "MarksInformation" : {
...          "Marks1" : 67,
...          "Marks2" :45,
...          "Marks3" : 78
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e77833abbc41e36cc3caeab")
}
> db.demo439.insertOne(
...    {
...       "Name" : "David",
...       "MarksInformation" : {
...          "Marks1" : 50,
...          "Marks2" :57,
...          "Marks3" : 68
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e77833abbc41e36cc3caeac")
}
> db.demo439.insertOne(
...    {
...       "Name" : "Bob",
...       "MarksInformation" : {
...          "Score1" : 65,
...          "Score2" :71,
...
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e77833bbbc41e36cc3caead")
}

在集合中顯示所有文件並使用 find() 方法 −

> db.demo439.find();

這將生成以下輸出 −

{ "_id" : ObjectId("5e77833abbc41e36cc3caeab"), "Name" : "Chris", "MarksInformation" : { "Marks1" : 67, "Marks2" : 45, "Marks3" : 78 } }
{ "_id" : ObjectId("5e77833abbc41e36cc3caeac"), "Name" : "David", "MarksInformation" : { "Marks1" : 50, "Marks2" : 57, "Marks3" : 68 } }
{ "_id" : ObjectId("5e77833bbbc41e36cc3caead"), "Name" : "Bob", "MarksInformation" : { "Score1" : 65, "Score2" : 71 } }

以下是投影欄位的查詢 −

> db.demo439.aggregate({
...    $project: {
...       "Name" : 1,
...       "Marks1": { $cond: [ { $eq:[ { $ifNull: [ "$MarksInformation.Marks1", 0 ] }, 0 ] },{ $ifNull: [ "$MarksInformation.Score1", 0 ] }, "$MarksInformation.Marks1" ] },
...       "Marks2": { $cond: [ { $eq:[ { $ifNull: [ "$MarksInformation.Marks2", 0 ] }, 0 ] }, { $ifNull: [ "$MarksInformation.Score2", 0 ] }, "$MarksInformation.Marks2" ] },
...    "Marks3": { $cond: [ { $eq:[ { $ifNull: [ "$MarksInformation.Marks3", 0] }, 0 ] }, { $ifNull: [ "$MarksInformation.Score3", 0 ] }, "$MarksInformation.Marks3" ] }
... }})

這將生成以下輸出 −

{ "_id" : ObjectId("5e77833abbc41e36cc3caeab"), "Name" : "Chris", "Marks1" : 67, "Marks2" : 45, "Marks3" : 78 }
{ "_id" : ObjectId("5e77833abbc41e36cc3caeac"), "Name" : "David", "Marks1" : 50, "Marks2" : 57, "Marks3" : 68 }
{ "_id" : ObjectId("5e77833bbbc41e36cc3caead"), "Name" : "Bob", "Marks1" : 65, "Marks2" : 71, "Marks3" : 0 }

更新於:2020 年 4 月 6 日

180 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

入門
廣告
© . All rights reserved.