[英]MongoDB delete document inside a collection by NodeJS
所以我想做的是,如果你看一下下面的圖片,就是通過它的 id 刪除transactions
中的一個文檔。
我試過的:
const result = await db.updateMany({ pipedrive_id: 999 }, { $pull: { transactions: { id: id } } });
正如這個 stackoverflow 帖子中所建議的那樣。 但它什么也沒做。
然后我嘗試了:
const result = await db.findOneAndDelete(
{
'transactions._id': { $in: id },
}
);
兩種情況下的id
都是 transactions 中transactions
的_id
。 但這並沒有像預期的那樣工作,因為它刪除了集合中的所有項目以及父項。
所以我有點卡住了,有什么幫助嗎?
問題是您嘗試遵循的答案不起作用。 (答案中的評論也是正確的)。 檢查這個例子以及它是如何失敗的。
如前所述,例如在 Node.JS 驅動程序中,Jira Ticket $pull 運算符不適用於點符號
這是預期的行為,查詢語言當前不支持。
所以你需要這個查詢:
db.updateOne({
"_id": 1,
"transactions._id": 1
},
{
"$pull": {
"transactions": {
"_id": 1
}
}
})
請注意$pull
object 中沒有點符號,而是定義了 object 本身。
這里的例子
所以,我有點實現了我的目標,但我打賭有適當的 mongodb 解決方案。 我猜這只是一種駭人聽聞的方式。
// fetch all documents inside transactions collection
const queryResult = await db.find({ pipedrive_id: 999 });
const idToRemove = 'some id';
if (queryResult.length) {
// filter out the ID's that needs to be deleted
const results = queryResult.transactions.filter((item) => idToRemove !== item['id']);
// update the document with the filtered ones (aka deleting the specified ones)
await db.updateOne(
{
pipedrive_id: 999
},
{
$set: { transactions: results },
}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.