Updating an Object in an Array

Hello everyone,

thank you for having me and potentially helping out already. I am currently stuck on an in my eyes simple? update query.

The scenario:
We save texts where users can save their own written solution. For the texts, we have our own collection the same as for the users. When the user submits a solution it is saved in the user Document in an array as an object containing the text ID and the solution itself. This works fine for the first time by using $push. When writing more text or editing this solution a new array object is created, instead of updating the one present:
Example:

{
userID: 1,
 solutions: [
   { textID: 2,
     solution: "some solution text"
   } 
]'
}

As mentioned I used $push with using the following filter: { userID: 1, solutions.textID: 2 } and it still created a new one :smiley:.
Maybe I am just too much into it and not able to look left and right here, that’s why I reached out to you. Is it a flaw with my data model or should I use aggregations?

Any help much appreciated :pray:
Stay save!

Hi @lucdoe,

Here is an example of how to update a field in a document in an array using the $ positional operator:

test:PRIMARY> db.coll.insert({userID:1,solutions: [{textID:2, solution: "the old text"}]})
WriteResult({ "nInserted" : 1 })
test:PRIMARY> db.coll.update({userID:1, "solutions.textID":2}, {$set: {"solutions.$.solution": "the new text"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
test:PRIMARY> db.coll.findOne()
{
	"_id" : ObjectId("602fa2f615271349f5e49e25"),
	"userID" : 1,
	"solutions" : [
		{
			"textID" : 2,
			"solution" : "the new text"
		}
	]
}

I hope this is what you wanted.

Cheers,
Maxime.

1 Like

Hey @MaBeuLux88, thanks for your quick answer, one yes this helps, but this is not really what I am aiming for. Just for clarity, I want to archive the outcome with one operation (if possible). Maybe I need to do it like you pointed out but it would be great to have it in one operation like $push, $set or similuar. Do you get where I am aiming to go with this?

So if the text is written for the first time it should work with the same operation as with when I am editing.
Sorry trying to structure my thoughts haha

Hello @lucdoe, here is a post with similar update operation you are looking for. Let me know if it works for you.

In the end, I went to this solution for everyone coming back:
In the backend I first executed findOne({ userID: X, textID: Y}) to see if there is a solution by this user on the given text. If I get back null I push a new object to the array.

Works and is a bit simpler than @Prasad_Saya’s solution :slight_smile:

Thanks again, everyone!

1 Like