如何在 MongoDB 中只保留單一文件,刪除集合中的所有其他文件?
要在 MongoDB 中只保留單一文件,刪除集合中的所有其他文件,請根據某些條件使用 remove()。讓我們建立一個包含文件的集合。以下是要查詢的內容
>db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c9de42d66697741252478")
}
>db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Mike","StudentAge":21,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c9dea2d66697741252479")
}
>db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9c9def2d6669774125247a")
}以下是使用 find() 方法顯示集合中所有文件的查詢內容
> db.removeAllDocumentsExceptOneDemo.find().pretty();
這將生成以下輸出
{
"_id" : ObjectId("5c9c9de42d66697741252478"),
"StudentName" : "Larry",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9c9dea2d66697741252479"),
"StudentName" : "Mike",
"StudentAge" : 21,
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c9c9def2d6669774125247a"),
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}以下是刪除集合中除單一文件(即 StudentAge 為 24)之外的所有文件的查詢內容
> db.removeAllDocumentsExceptOneDemo.remove({ StudentAge: { $ne: 24 } } );
WriteResult({ "nRemoved" : 2 })現在讓我們檢查所有文件。以下是查詢內容
> db.removeAllDocumentsExceptOneDemo.find().pretty();
以下是僅顯示單一文件的輸出
{
"_id" : ObjectId("5c9c9def2d6669774125247a"),
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP