问题描述
我正在建立一个投票系统,其中的对象将具有一个名为scores
的数组,只要该对象合格,只要不存在相同的ID,就会在该数组中输入一条记录.
I am making a voting system in which an object will have an array called scores
, every time it is qualified a record will be entered to this array as long as the same id does not exist.
示例文档:
{
name:"jose luis",
scores:[]
}
用户推送:
{id:1,stars:5}
更新后的文档:
{
name:"jose luis",
scores:[{id:1,stars:5}]
}
用户第二次按下:
{id:1,stars:4}
更新后的文档:
{
name:"jose luis",
scores:[{id:1,stars:4}]
} //this should update the value of the stars under the array element with the existing id.
我已经尝试过:
Politico.update(
{ name: "jose luis" },
{
$setOnInsert: { "$scores.id": body.req.id},
"$addToSet": {
scores: {
"id": body.req.id,
"starts": body.req.stars
}
}
},
{ upsert: true }
我已经尝试过了,但是没有用,如何解决?非常感谢.
I have tried this but it doesn't work, how can I fix it? Thanks a lot.
推荐答案
在MongoDB 4.2
或更高版本上,您可以使用聚合管道在更新中,请尝试以下查询:
On MongoDB 4.2
or above as you can use aggregation-pipeline in updates, try below query :
Politico.updateOne(
{ name: "jose luis" },
[{
$addFields: {
scores: {
$reduce: {
input: "$scores",
initialValue: [{ id: 1, stars: 5 }], // Input
in: {
$cond: [
{ $in: ["$$this.id", "$$value.id"] }, /** Check id exists in 'scores' array */
"$$value", /** If YES, return input */
{ $concatArrays: ["$$value", ["$$this"]] }/** If NO, concat value(holding array) with current object as array */
]
}
}
}
}
}]);
您可能不需要{ upsert: true }
,因为您没有使用name : "jose Luis"
&各自的scores
数组.但是,如果您想这样做:
You might not need { upsert: true }
as you're not writing a new document with name : "jose Luis"
& respective scores
array. But if you wanted to do that :
Politico.updateOne(
{ name: "jose luis" },
[{
$addFields: {
scores: {
$reduce: {
input: "$scores",
initialValue: [{ id: 1, stars: 5 }], // Input
in: {
$cond: [
{ $in: ["$$this.id", "$$value.id"] }, /** Check id exists in 'scores' array */
"$$value", /** If YES, return input */
{ $concatArrays: ["$$value", ["$$this"]] }/** If NO, concat value(holding array) with current object as array */
]
}
}
}
}
},
{$addFields : {scores : { $ifNull: [ "$scores", {id : 13, stars: 3} ] }}} /** This additional 'addFields' will add 'scores' array with input object to newly created doc */
],{upsert : true});
这篇关于将元素添加到数组(如果存在),不添加,如果存在,则更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!