向所有嵌入的数组文档添加随机数



此代码为所有嵌入文档添加一个随机数,但对于每个嵌入文档都需要一个随机数。

app.patch("/updatemany", async (req, res, next) => {
let a = await listingsAndReview.updateOne(
{ reviews: { $ne: [] } },
{
$set: {
"reviews.$[].rating": Math.round(Math.random() * 4 * 10) / 10 + 1,
},
},
{
upsert: true,
}
);
res.send(a);
});

一个选项是使用update with pipeline,以及$rand:

db.collection.updateOne({ reviews: { $ne: [] } },
[
{
$set: {
reviews: {
$map: {
input: "$reviews",
in: {
$mergeObjects: [
"$$this",
{rating: {$rand: {}}}
]
}
}
}
}
}
])

看看它在操场的例子中是如何工作的

$rand取值范围为0 ~ 1。您可以使用$multiply,$add…来控制范围

最新更新