[英]How to move documents in mongodb between collections
如何將一個現有文檔從一個集合移動到另一個集合?
基本上,我所擁有的是一個客戶模式:
const customerSchema = new mongoose.Schema ({
firstname: String,
lastname: String,
email: String,
});
和它的 Model:
const Customer = new mongoose.model('Customer', customerSchema);
現在我想將一個文檔移動到存檔集合中。 所以我想,我創建一個新的 model,如下所示:
const CustomerArchive = new mongoose.model('CustomerArchive', customerSchema);
然后,當有人單擊帶有 formaction: "/archive-data" 的按鈕時,需要將數據集從 Customer 集合移動到 CustomerArchive 集合。
[
{
_id: new ObjectId("6325ba96f228119e479963ca"),
firstname: 'Testuser',
lastname: 'Testuser',
email: 'test@user',
__v: 0
}
有沒有辦法將一個文檔移動到另一個集合而無需再次定義每個屬性?
app.post("/archive-data", (req, res) => {
const docId = req.body.archiveButton;
Customer.find({ _id: docId }, (err, document) => {
CustomerArchive.create([document])
})
})
這是我到目前為止所擁有的,它確實有效,但必須有更好的方法 - 即使涉及唯一 ID 或重復項:
app.post("/archive-data", (req, res) => {
const docId = req.body.archiveButton;
Customer.find({ _id: docId}, (err, document) => {
CustomerArchive.create({
_id: document[0]._id,
firstname: document[0].firstname,
lastname: document[0].lastname,
email: document[0].email
});
Customer.findByIdAndRemove(docId, (err) => {
if (!err) {
res.redirect("/customers");
} else {
console.log(err);
}
});
})
});
而且,另一個問題:有誰知道 mongodb 中的 ID 在 collections 中是否唯一? 就像在這種情況下:我將文檔從集合客戶移動到存檔集合,但是,如果有人決定將存檔文檔移回生產集合 - id 已經存在的可能性可能非常低,但在巨大的客戶數據庫它可能會發生
您可以像這樣簡單地編寫一個簡短的聚合管道:
app.post("/archive-data", async (req, res) => {
const docId = req.body.archiveButton;
await Customer.aggregate([
{ $match:
{ _id: docId}
},
{
$merge: {
into: "customerArchive",
on: "_id",
whenMatched: "replace",
whenNotMatched: "insert"
}
}
]).exec((err, res) => console.log(`${err} ${res}`));
Customer.findByIdAndRemove(docId, (err) => {
if (!err) {
res.redirect("/customers");
} else {
console.log(err);
}
});
});
在管道中,我們首先匹配所需的文檔並使用$merge將其合並到customerArchive
集合中。
如果您按照 Mongodb 的建議使用ObjectId
,您可以確定它在 collections 中是唯一的,因為它是時間戳、隨機數和自動遞增計數器的組合,因此發生沖突的可能性極小.
此外,創建一個新集合來存儲僅存檔客戶,似乎有點過頭了,您可以減少很多工作,只需將 boolean 值archive
存儲在客戶的 collections 本身中,表示客戶是否已存檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.