Reputation: 63
I'm working on a simple web forum system and i've come across this problem when trying to give the users a way to post messages to a thread. Each thread is a document inside an array in a group document, and then inside each thread document is a message array which should contain message documents.
My query is:
db.grops.update({},{$push:{"threads.$[elem].messages":"hello"}},{arrayFilters:[{"elem._id":ObjectId("602645582fa6cb13f8449057")}]})
And my group table of the db is:
{
"_id" : ObjectId("60264286f5440e114c189212"),
"members" : [ ],
"name" : "Computer Science London",
"location" : {
"coordinates" : [
51.503391,
-0.12763
],
"_id" : ObjectId("60264286f5440e114c189213"),
"type" : "Point"
},
"description" : "A group for computing students to learn, talk and share!",
"pictureURL" : "/images/computer.jpg",
"threads" : [
{
"_id" : ObjectId("602645582fa6cb13f8449057"),
"title" : "What is a lambda function",
"openingPost" : "I am reading this textbook and it mentions this thing called a lambda function, but it doesnt seem to outline what it is. Can someone help me understand?",
"postedBy" : "ElBarto88",
"updatedAt" : ISODate("2021-02-12T09:07:36.833Z"),
"createdAt" : ISODate("2021-02-12T09:07:36.833Z"),
"messages" : [ ]
},
{
"_id" : ObjectId("602645af2fa6cb13f8449058"),
"title" : "How do i install linux?",
"openingPost" : "This server assignment requires i have linux installed, how do install it?",
"postedBy" : "ElBarto88",
"updatedAt" : ISODate("2021-02-12T09:09:03.123Z"),
"createdAt" : ISODate("2021-02-12T09:09:03.123Z"),
"messages" : [ ]
}
],
"createdAt" : ISODate("2021-02-12T08:55:34.273Z"),
"updatedAt" : ISODate("2021-02-12T09:09:03.123Z"),
"__v" : 0
}
I can not seem to get any query to get any matches, and then push "hello" to the sub-array. I have also tried matching by {"elem.postedBy:"ElBarto88"}
, to no avail. For all the queries involving arrayFilters i get back:
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
Currently i am just testing by posting the queries directly to the mongo shell(i am using mongoose for the main application). My shell version is: v4.4.2 , and my server version (MongoDB atlas cluster) is: v4.4.3
Upvotes: 0
Views: 98
Reputation: 63
I've been really stupid, it was a spelling mistake causing my problems. group
not grop
, not the code.
facepalms and closes thread quickly
Upvotes: 0
Reputation: 1396
I believe you can do this:
db.grops.update({"threads.$._id":ObjectId("602645582fa6cb13f8449057")},{$push:{"threads.$.messages":"hello"}})
Let me know if it doesn't work. Remember: it wil update ONLY FIRST matching element.
Upvotes: 1