所以基本上我有這個資料
{
company: {
subscriptions: [
{
"name": "test1",
"updatedAt": ISODate("2021-10-19T06:40:33.583Z")
},
{
"name": "test2",
"updatedAt": ISODate("2021-10-19T06:40:33.583Z")
},
{
"services": {
"1": {
"createdAt": ISODate("2021-10-19T06:40:33.583Z"),
"updatedAt": ISODate("2021-10-19T06:40:33.583Z")
}
},
"updatedAt": ISODate("2021-10-19T06:40:33.583Z")
}
]
}
}
目前我不知道這些資料是如何插入到集合中的。
奇怪的資料是這個。
{
"services": {
"1": {
"createdAt": ISODate("2021-10-19T06:40:33.583Z"),
"updatedAt": ISODate("2021-10-19T06:40:33.583Z")
}
},
"updatedAt": ISODate("2021-10-19T06:40:33.583Z")
}
如何使用 mongodb $pull 洗掉訂閱陣列中的這個?
uj5u.com熱心網友回復:
基于@Takis_ 的回答,我找到了一個解決方案。這是我所做的
const cursor = await Company.find({
$and: [
{
"subscriptions": { $exists: true, $ne: [] }
}
]
}).cursor();
await cursor.eachAsync(async company => {
let isUpdate = false;
const found = find(company.subscriptions, subscription => subscription.name === undefined);
if (!found) return
try {
const res = await Company.updateOne(
{
"_id": mongoose.Types.ObjectId(company._id),
},
{
$pull: { subscriptions: { name: { $exists: false } } }
}
);
} catch(err) {
log(`ERROR removing subscription entry for company ${company.name} - ${company._id}`);
}
})
uj5u.com熱心網友回復:
查詢1
- $pull,如果成員沒有名為 name 的欄位,它會被洗掉
測驗代碼在這里
db.collection.updateMany({},
{
$pull: {
"company.subscriptions": {
name: {
"$exists": false
}
}
}
})
查詢2
- 管道的替代方式
- 這將洗掉陣列的一個成員,如果沒有欄位
name(或名稱為 false/null) - 您不想洗掉的服務沒有名稱,因此將被過濾掉
管道更新需要 MongoDB >= 4.2
測驗代碼在這里
db.collection.updateMany({},
[
{
"$set": {
"company.subscriptions": {
"$filter": {
"input": "$company.subscriptions",
"cond": "$$this.name"
}
}
}
}
])
如果您的 updateMany 方法不接受管道,您可以像命令一樣運行它
db.runCommand(
{
update: "yourCollection",
updates: [
{
q: { },
u: [
{
"$set": {
"company.subscriptions": {
"$filter": {
"input": "$company.subscriptions",
"cond": "$$this.name"
}
}}}
],
multi: true
}
],
ordered: false
}
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326149.html
