MongoDB 查詢可向已建立的集合中新增文件


要向已建立的集合中新增文件,請在 MongoDB 中使用 $push。讓我們使用文件建立集合

> db.demo177.insertOne(
   { "Id": "101", "details": [  
      { "StudentName": "Chris",  "Scores": [67, 71, 74], "SubjectName": ["MySQL", "Java"]  },
      { "StudentName": "David", "Scores": [89,98,45], "SubjectName": ["PL/SQL", "C"] } ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e384b2b9e4f06af551997f4")
}

透過 find() 方法顯示集合中的所有文件 −

> db.demo177.find().pretty();

這將產生以下輸出 −

{
   "_id" : ObjectId("5e384b2b9e4f06af551997f4"),
   "Id" : "101",
   "details" : [
      {
         "StudentName" : "Chris",
         "Scores" : [ 67, 71, 74 ],
         "SubjectName" : [ "MySQL", "Java" ]
      },
      {
         "StudentName" : "David",
         "Scores" : [ 89, 98, 45 ],
         "SubjectName" : [ "PL/SQL", "C" ]
      }
   ]
}

以下是向已建立的集合中新增文件的查詢 −

> db.demo177.update({"Id": "101"},
...{
...   $push: {
...      "details": {
...         "StudentName": "Chris",
...         "Scores": [90, 91, 94],
...         "SubjectName": ["MongoDB", "SQL Server"]
...      }
...   }
...});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

透過 find() 方法顯示集合中的所有文件 −

> db.demo177.find().pretty();

這將產生以下輸出 −

{
   "_id" : ObjectId("5e384b2b9e4f06af551997f4"),
   "Id" : "101",
   "details" : [
      {
         "StudentName" : "Chris",
         "Scores" : [ 67, 71, 74 ],
         "SubjectName" : [ "MySQL", "Java" ]
      },
      {
         "StudentName" : "David",
         "Scores" : [ 89, 98, 45 ],
         "SubjectName" : [ "PL/SQL", "C" ]
      },
      {
         "StudentName" : "Chris",
         "Scores" : [ 90, 91, 94 ],
         "SubjectName" : [ "MongoDB", "SQL Server" ]
      }
   ]
}

更新日期:27-Mar-2020

128 次瀏覽

開啟你的 事業

完成課程以獲取認證

立即開始
廣告
© . All rights reserved.