如何無條件地從 MongoDB 中的陣列提取全部元素?
你可以為此使用 $set 運算子。讓我們首先建立一個包含文件的集合 -
> db.pullAllElementDemo.insertOne(
... {
... "StudentId":101,
... "StudentDetails" : [
... {
...
... "StudentName": "Carol",
... "StudentAge":21,
... "StudentCountryName":"US"
... },
... {
... "StudentName": "Chris",
... "StudentAge":24,
... "StudentCountryName":"AUS"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdd9c8685b30d09a7111e4")
}
> db.pullAllElementDemo.insertOne(
... {
... "StudentId":102,
... "StudentDetails" : [
... {
...
... "StudentName": "Robert",
... "StudentAge":27,
... "StudentCountryName":"UK"
... },
... {
... "StudentName": "David",
... "StudentAge":23,
... "StudentCountryName":"US"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdd9f7685b30d09a7111e5")
}以下是使用 find() 方法顯示集合中所有文件的查詢 -
> db.pullAllElementDemo.find().pretty();
這將產生以下輸出 -
{
"_id" : ObjectId("5ccdd9c8685b30d09a7111e4"),
"StudentId" : 101,
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
]
}
{
"_id" : ObjectId("5ccdd9f7685b30d09a7111e5"),
"StudentId" : 102,
"StudentDetails" : [
{
"StudentName" : "Robert",
"StudentAge" : 27,
"StudentCountryName" : "UK"
},
{
"StudentName" : "David",
"StudentAge" : 23,
"StudentCountryName" : "US"
}
]
}以下是無條件地從 MongoDB 中的陣列提取所有元素的查詢。在此,我們已使用 $set 刪除具有 StudentId 102 的 StudentDetails -
> db.pullAllElementDemo.update( {StudentId:102}, { "$set": { "StudentDetails": [] }} );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })讓我們顯示來自上述集合的所有文件,以檢查特定元素是否已從陣列中提取出來 -
> db.pullAllElementDemo.find().pretty();
這將產生以下輸出 -
{
"_id" : ObjectId("5ccdd9c8685b30d09a7111e4"),
"StudentId" : 101,
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
]
}
{
"_id" : ObjectId("5ccdd9f7685b30d09a7111e5"),
"StudentId" : 102,
"StudentDetails" : [ ]
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP