game_data: [{
id: 'HUH',
name: 'GTA'
story: 'ahhhh'
}]
I have a field like above. I want to check incoming data to avoid duplicate on the value id
.
incomingg_dataA: {
id: 'HUH',
name: 'Dota2'
story: 'hmmm'
}
Like this case, if the incomingg_dataA
contains the same id HUH
. I want to use that value to $addToSet
. If the id is different
incomingg_dataB: {
id: 'HUUUH',
name: 'Dota2'
story: 'hmmm'
}
then, it would be
game_data: [{
id: 'HUH',
name: 'GTA'
story: 'ahhhh'
},
{
id: 'HUUUH',
name: 'Dota2'
story: 'hmmm'
}];
I could do the entire document as $addToSet
but then, I am kinda afraid that someone will just change the story
part and it will still be registered.
Is there any way that I can do this with $addToSet
or do I just have to do the.find() and callback function?
You have to add the $ne
condition in your find query with the id
value you want to avoid duplicate.
db.col.update({
// All the find conditions you want
// Plus the below condition
"game_data.id": {"$ne": incomingg_dataB['id']}, // Updated only when the `id` is not already present in the array
}, {
"$push": {
"game_data": incomingg_dataB,
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.