gpt4 book ai didi

javascript - 在 MongoDB 中的 updateMany() 之前使用 $unwind

转载 作者:行者123 更新时间:2023-12-03 02:08:41 27 4
gpt4 key购买 nike

在我的 MongoDB/Node 后端中,我有一个函数,可以根据传入的订阅 _ids 更新标题为 subscriptionEnd 的字段上的日期。它看起来像这样:

    try {
db.collection('clients').updateMany(
{ "subscription._id": { $in: mongoArrSubscription } },
{ $set : {"subscription.$.subscriptionEnd": lastDayOfMonth } },
function (err, res) {
if (err) throw err;
});
res.sendStatus(200);
} catch (e) {
console.log(e);
}
}

这按原样工作。然而,照原样,这只会针对“订阅”数组中的第一个元素。我现在意识到我们有实例,同一个数组中有两个元素可以传入。所以,我的想法是在这个函数中使用 $unwind ,首先 $unwind “订阅”数组。然而,我对语法有点不清楚,以及这是否可行。

我的展开聚合如下所示:

Client.aggregate( [ { $unwind : "$subscription" } ] );

有没有办法可以将这个 $unwind 聚合链接在一起,以便它发生在我的 try/catch block 中的 updateMany() 之前?该语法是什么样的?我是否将这些操作链接在一起,或者将 $unwind 作为参数传递给 updateMany()

我尝试了这个,将 $unwind 操作作为第一个参数传递:

    try {
db.collection('clients').updateMany( { $unwind : "$subscription" },
{ "subscription._id": { $in: mongoArrSubscription } },
{ $set : {"subscription.$.subscriptionEnd": lastDayOfMonth } },
function (err, res) {
if (err) throw err;
});
res.sendStatus(200);
} catch (e) {
console.log(e);
}
}

...但它出错了:

MongoError: Unknown modifier: $unwind

所以也许我需要先进行聚合 $unwind,作为单独的操作,然后运行 ​​updateMany()

更新:有人指出 $unwind 不能与 updateMany() 一起使用,所以也许我需要执行 $unwind 操作首先单独运行,然后运行我的 updateMany() 操作?

最佳答案

您可以使用较低版本的聚合和批量写入来模拟 3.6 多重更新。

类似的东西

var bulk = db.getCollection('clients').initializeUnorderedBulkOp();
var count = 0;
var batch = 1;

db.getCollection('clients').aggregate([
{$match:{"subscription._id":{$in:mongoArrSubscription}}},
{$unwind:"$subscription"},
{$match:{"subscription._id":{$in:mongoArrSubscription}}},
{$project: {_id:0, subscription_id:"$subscription._id"}}
]).forEach(function(doc){
var subscription_id = doc.subscription_id;
bulk.find({"subscription._id":subscription_id}).updateOne(
{$set:{"subscription.$.subscriptionEnd": lastDayOfMonth}}
);
count++;
if (count == batch) {
bulk.execute();
bulk = db.getCollection('clients').initializeUnorderedBulkOp();
count = 0;
}
});

if (count > 0) {
bulk.execute();
}

关于javascript - 在 MongoDB 中的 updateMany() 之前使用 $unwind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49676942/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com