I have the following collection
{
"_id" : ObjectId("57315ba4846dd82425ca2408"),
"myarray" : [
{
userId : ObjectId("570ca5e48dbe673802c2d035"),
point : 5
},
{
userId : ObjectId("613ca5e48dbe673802c2d521"),
point : 2
},
]
}
These are my questions
I want to push into myarray if userId doesn't exist, it should be appended to myarray. If userId exists, it should be updated to point.
I found this
db.collection.update({
_id : ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId" : ObjectId("570ca5e48dbe673802c2d035")
}, {
$set: { "myarray.$.point": 10 }
})
But if userId doesn't exist, nothing happens.
and
db.collection.update({
_id : ObjectId("57315ba4846dd82425ca2408")
}, {
$push: {
"myarray": {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
})
But if userId object already exists, it will push again.
What is the best way to do this in MongoDB?
Try this
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{ $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{ $push: {"myarray": {
userId:ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}}
)
Explination:
in the first statment $pull removes the element with userId= ObjectId("570ca5e48dbe673802c2d035") from the array on the document where _id = ObjectId("57315ba4846dd82425ca2408")
In the second one $push inserts
this object { userId:ObjectId("570ca5e48dbe673802c2d035"), point: 10 } in the same array.
The accepted answer by Flying Fisher is that the existing record will first be deleted, and then it will be pushed again.
A safer approach (common sense) would be to try to update the record first, and if that did not find a match, insert it, like so:
// first try to overwrite existing value
var result = db.collection.update(
{
_id : ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
},
{
$set: {"myarray.$.point": {point: 10}}
}
);
// you probably need to modify the following if-statement to some async callback
// checking depending on your server-side code and mongodb-driver
if(!result.nMatched)
{
// record not found, so create a new entry
// this can be done using $addToSet:
db.collection.update(
{
_id: ObjectId("57315ba4846dd82425ca2408")
},
{
$addToSet: {
myarray: {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
}
);
// OR (the equivalent) using $push:
db.collection.update(
{
_id: ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId": {$ne: ObjectId("570ca5e48dbe673802c2d035"}}
},
{
$push: {
myarray: {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
}
);
}
This should also give (common sense, untested) an increase in performance, if in most cases the record already exists, only the first query will be executed.
There is a option called update documents with aggregation pipeline starting from MongoDB v4.2,
check condition $cond if userId in myarray.userId or not
if yes then $map to iterate loop of myarray array and check condition if userId match then merge with new document using $mergeObjects
if no then $concatArrays to concat new object and myarray
let _id = ObjectId("57315ba4846dd82425ca2408");
let updateDoc = {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
};
db.collection.update(
{ _id: _id },
[{
$set: {
myarray: {
$cond: [
{ $in: [updateDoc.userId, "$myarray.userId"] },
{
$map: {
input: "$myarray",
in: {
$mergeObjects: [
"$$this",
{
$cond: [
{ $eq: ["$$this.userId", updateDoc.userId] },
updateDoc,
{}
]
}
]
}
}
},
{ $concatArrays: ["$myarray", [updateDoc]] }
]
}
}
}]
)
Playground
Unfortunately "upsert" operation is not possible on embedded array. Operators simply do not exist so that this is not possible in a single statement.Hence you must perform two update operations in order to do what you want. Also the order of application for these two updates is important to get desired result.
I haven't found any solutions based on a one atomic query. Instead there are 3 ways based on a sequence of two queries:
always $pull (to remove the item from array), then $push (to add the updated item to array)
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{ $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{
$push: {
"myarray": {
userId:ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
}
)
try to $set (to update the item in array if exists), then get the result and check if the updating operation successed or if a $push needs (to insert the item)
var result = db.collection.update(
{
_id : ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")
},
{
$set: {"myarray.$.point": {point: 10}}
}
);
if(!result.nMatched){
db.collection.update({_id: ObjectId("57315ba4846dd82425ca2408")},
{
$addToSet: {
myarray: {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
);
always $addToSet (to add the item if not exists), then always $set to update the item in array
db.collection.update({_id: ObjectId("57315ba4846dd82425ca2408")},
myarray: { $not: { $elemMatch: {userId: ObjectId("570ca5e48dbe673802c2d035")} } } },
{
$addToSet : {
myarray: {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
},
{ multi: false, upsert: false});
db.collection.update({
_id: ObjectId("57315ba4846dd82425ca2408"),
"myArray.userId": ObjectId("570ca5e48dbe673802c2d035")
},
{ $set : { myArray.$.point: 10 } },
{ multi: false, upsert: false});
1st and 2nd way are unsafe, so transaction must be established to avoid two concurrent requests could push the same item generating a duplicate.
3rd way is safer. the $addToSet adds only if the item doesn't exist, otherwise nothing happens. In case of two concurrent requests, only one of them adds the missing item to the array.
Possible solution with aggregation pipeline:
db.collection.update(
{ _id },
[
{
$set: {
myarray: { $filter: {
input: '$myarray',
as: 'myarray',
cond: { $ne: ['$$myarray.userId', ObjectId('570ca5e48dbe673802c2d035')] },
} },
},
},
{
$set: {
myarray: {
$concatArrays: [
'$myarray',
[{ userId: ObjectId('570ca5e48dbe673802c2d035'), point: 10 },
],
],
},
},
},
],
);
We use 2 stages:
filter myarray (= remove element if userId exist)
concat filtered myarray with new element;
When you want update or insert value in array try it
Object in db
key:name,
key1:name1,
arr:[
{
val:1,
val2:1
}
]
Query
var query = {
$inc:{
"arr.0.val": 2,
"arr.0.val2": 2
}
}
.updateOne( { "key": name }, query, { upsert: true }
key:name,
key1:name1,
arr:[
{
val:3,
val2:3
}
]
In MongoDB 3.6 it is now possible to upsert elements in an array.
array update and create don't mix in under one query, if you care much about atomicity then there's this solution:
normalise your schema to,
{
"_id" : ObjectId("57315ba4846dd82425ca2408"),
userId : ObjectId("570ca5e48dbe673802c2d035"),
point : 5
}
You could use a variation of the .forEach/.updateOne method I currently use in mongosh CLI to do things like that. In the .forEach, you might be able to set all of your if/then conditions that you mentioned.
Example of .forEach/.updateOne:
let medications = db.medications.aggregate([
{$match: {patient_id: {$exists: true}}}
]).toArray();
medications.forEach(med => {
try {
db.patients.updateOne({patient_id: med.patient_id},
{$push: {medications: med}}
)
} catch {
console.log("Didn't find match for patient_id. Could not add this med to a patient.")
}
})
This may not be the most "MongoDB way" to do it, but it definitely works and gives you the freedom of javascript to do things within the .forEach.
Sounds messy, I know.
The document I'm modifying is structured like this:
{
"_id":12345,
"name":"harold",
"basicData":{
"devices":[
{
"id":7654,
"relatedJson":{
"make":"sony",
"equipmentID":"asdf"
}
},
{
"id":9493
}
],
"car":"toyota"
}
}
I can't quite get the code right. This is what I have:
db.serviceAgreement.updateMany({"basicData.devices.relatedJson.equipmentID": {$exists: true}},
[
{
$set: {
"basicData.devices": {
$map: {
input: "$basicData.devices", in: {
$mergeObjects: ["$$this.relatedJson",
{equipmentId: "$$this.relatedJson.equipmentID",}]
}
}
}
}
},
{
$unset: "basicData.devices.relatedJson.equipmentID"
}
])
So my understanding of this script is that I'm calling $set to set the field basicData.devices, then I'm setting it to that same list, but before I do that I'm merging the documents relatedJson and a new document {equipmentId : "$$this.relatedJson.equipmentID",} which has the value equipmentId set to the same value as the equipmentID in the relatedJson object.
Then, I'm replacing the relatedJson document with the newly created equipmentId (not my intention).
And finally, deleting the original equipmentID - which doesn't actually exist any more because I've replaced the whole relatedJson object.
How can I insert the new equipmentId into the relatedJson object, instead of replacing it entirely.
I have tried variations of the above script that do all sorts of things, inserting a copy of relatedJson into itself, inserting a copy of devices into relatedJson, deleting everything inside devices, but I can't get it to do what I want.
I feel I'm close to a solution, and maybe I need to modify the $input: but I can't figure out how, or maybe my approach is totally wrong.
Any help would be greatly appreciated.
The end result should be the same document, but relatedJson.equipmentID should be renamed relatedJson.equipmentId (with a lower-case 'd' at the end);
You're close, you just had some syntax issues.
The update should look like this:
db.collection.updateMany({"basicData.devices.relatedJson.equipmentID": {$exists: true}},
[
{
$set: {
"basicData.devices": {
$map: {
input: "$basicData.devices",
in: {
$mergeObjects: [
"$$this",
{
$cond: [
{
$ne: [
"$$this.relatedJson",
undefined
]
},
{
relatedJson: {
$mergeObjects: [
"$$this.relatedJson",
{
equipmentId: "$$this.relatedJson.equipmentID"
}
]
}
},
{}
]
}
]
}
}
}
}
},
{
$unset: "basicData.devices.relatedJson.equipmentID"
}
])
Mongo Playground
I am trying to query my collection of matches (games) and find if a certain user has already sent data to the 'reportMessages' array of Objects.
const results = await Match.findOne({ 'users': req.params.userIdOfReportSender, '_id': req.params.matchId, 'reportMessages.sentBy': req.params.userIdOfReportSender }, 'reportMessages' )
However, the above query returns the following:
{
_id: 5fd382c65d5395e0778f2f8a,
reportMessages: [
{
_id: 5fd610f27ae587189c45b6ca,
content: 'jajatest',
timeStamp: 2020-12-13T13:02:42.102Z,
sentBy: 'XbVvm6g3nsRmPg3P1pBvVl84h6C2'
},
{ sentBy: "'anotheruser123" }
]
}
How can I get it to only return the first reportMessage, i.e. the one sent by XbVvm6g3nsRmPg3P1pBvVl84h6C2?
Mongoose findOne docs (https://mongoosejs.com/docs/api.html#model_Model.findOne) show that you can provide arguments to say which fields to select (in their case 'name length' but don't show a way to only select the fields in case they match a certain condition.
Is this even possible? Tried googling this seemingly easy question for quite some time without success
Kind regards
You can get only the subdocument you want with this aggregation query:
Match.aggregate([
{
$match: { _id: req.params.matchId }
},
{
$project: {
reportMessages: {
$filter: {
input: '$reportMessages',
as: 'msg',
cond: { $eq: ['$$msg.sentBy', req.params.userIdOfReportSender] }
}
}
}
},
{
$project: {
reportMessage: { $arrayElemAt: [ '$reportMessages', 0 ] },
}
},
{ $replaceWith: '$reportMessage' }
]);
Note that you only need to specify the document _id to get a single result, since _ids are unique.
I have a mongo collection where docs have been already stored. The structure is of a single doc is something like this:
"_id":ObjectId("55c3043ab165fa6355ec5c9b"),
"address":{
"building":"522",
"coord":[
-73.95171,
40.767461
],
"street":"East 74 Street",
"zipcode":"10021"
}
}
Now I want to update the doc by inserting a new field "persons" with value being a list of objects [{"name":"marcus", "contact":"420"}, {"name":"modiji", "contact":"111"}], so after insertion the above doc should look like this:
"_id":ObjectId("55c3043ab165fa6355ec5c9b"),
"address":{
"building":"522",
"coord":[
-73.95171,
40.767461
],
"street":"East 74 Street",
"zipcode":"10021"
},
"persons":[
{
"name":"marcus",
"contact":"420"
},
{
"name":"modiji",
"contact":"111"
}
]
}
Can anyone please help me with then correct $set syntax? Also, it would be really helpful if anyone can suggest an efficient way to update a key's value, which is a list of objects so that I can push some new objects inside the existing list.
You can use the updateOne command along with $set operator to achieve it.
db.<Collection-Name>.updateOne({
"_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
"$set": {
"persons":[
{
"name":"marcus",
"contact":"420"
},
{
"name":"modiji",
"contact":"111"
}
]
}
})
If you want to push additional data into the array, you can use the below command.
db.<Collection-Name>.updateOne({
"_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
"$push": {
"persons": {
"name":"sample",
"contact":"1234"
}
}
})
To push multiple arrays of objects in a single command, use the below query
db.<Collection-Name>.updateOne({
"_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
"$push": {
"persons": {
"$each": [
{
"name":"sample1",
"contact":"5678"
},
{
"name":"sample2",
"contact":"90123"
}
]
}
}
})
I have a collection looks like
{
"Aid":12234,
"items":{
"itemId":"SP897474",
"Blocks":[
{
"blockId":"W23456",
"name":"B1",
"innerBlock":[
{
"id":"S23490",
"name":"IB1",
"state":true
},
{
"id":"S23491",
"name":"IB2",
"state":true
},
{
"id":"S23492",
"name":"IB3",
"state":true
}
],
"active":true
},
{
"blockId":"W23457",
"name":"B2",
"innerBlock":[
{
"id":"S23482",
"name":"IB1",
"state":true
},
{
"id":"S23483",
"name":"IB2",
"state":true
}
],
"active":false
}
]
},
"active":true
}
I'm not able to update fields that is of innerBlock array, specially name, status because of nesting. Basically, I wanted to update mentioned fields .Iam already try this query
User.update({
"items.Blocks.innerBlock.id": req.body.id,
"Aid": req.body.Aid
}, {
"$set": {
"items.Blocks.$.InnerBlock.$.name": req.body.name
}
})
It shows an error given below
"errmsg": "Too many positional (i.e. '$') elements found in path 'items.Blocks.$.InnerBlock.$.name'"
I'm not sure how to fix it.What can be the query in mongo shell? Thanks.
Only one positional operator available right now with mongoDB. There are opened feature request for that https://jira.mongodb.org/browse/SERVER-831
check the answer https://stackoverflow.com/a/14855633/2066271