Reputation: 1
I want to add "3" to all "seenBy" array which is inside "Conversation" array.
{
_id : 1,
name : "name",
email : "email",
conversation : [
{
message : "Hai",
seenBy : [1,2]
},
{
message : "Hai",
seenBy : [1,2]
},
{
message : "Hai",
seenBy : [1,2]
}
]
}
Expected result :
{
name : "name",
email : "email",
conversation : [
{
message : "Hai",
seenBy : [1,2,3]
},
{
message : "Hai",
seenBy : [1,2,3]
},
{
message : "Hai",
seenBy : [1,2,3]
}
]
}
My code :
DB.Users.update({_id : 1}, {$addToSet : {"conversation.$[].seenBy" : 3}}, {}, function(err, result){
console.log(err);
console.log(result)
})
I get this error :
MongoError: cannot use the part (conversation of conversation.$[].seenBy) to traverse the element
Thanks in advance.
Upvotes: 0
Views: 46
Reputation: 10148
This is the way you can access nested array in document and push in it
Something like
db.Users.update(
{},
{ "$push": {"conversation.$[].seenBy": 3}}
)
Note. This will add 3
to all of your documents. You can add any filter based on your requirements
Upvotes: 0
Reputation: 3459
You're not specifying _id
field in the data set u mentioned:
{
name : "name",
email : "email",
conversation : [
{
message : "Hai",
seenBy : [1,2]
},
{
message : "Hai",
seenBy : [1,2]
},
{
message : "Hai",
seenBy : [1,2]
}
]
}
So, MongoDB add an ObjectID
automatically, so you need to specify that. _id:1
will work if u have the specified _id
in the DB. I'm getting proper output using your above query:
So, the issue is with your mongoose code and not with the Mongo query.
Upvotes: 1