Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

mongodb - Meteor mongo updating nested array

Example document:

{
"_id" : "5fTTdZhhLkFXpKvPY",
"name" : "example",
"usersActivities" : [ 
    {
        "userId" : "kHaM8hL3E3As7zkc5",
        "startDate" : ISODate("2015-06-01T00:00:00.000Z"),
        "endDate" : ISODate("2015-06-01T00:00:00.000Z")
    }
]
}

I'm new in mongoDB and I read other questions about updating nested array and I can't do it properly. What I want to do is to change startDate and endDate for user with given userId. My problem is that it always pushes new object to array instead of changing object with given userId.

Activity.update( 
    _id: activityId, usersActivities: {
         $elemMatch: {
             userId: Meteor.userId()
         }
     }},
    {
        $push: {
            'usersActivities.$.startDate': start,
            'usersActivities.$.endDate': end
         }
    }
);

I will be really glad of help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So the first thing to say here is the $elemMatch is not required in your case as you only want to match on a single array property. You use that operator when you need "two or more" properties from the same array element to match your conditions. Otherwise you just use "dot notation" as a standard.

The second case here is with $push, where that particular operator means to "add" elements to the array. In your case you just want to "update" so the correct operator here is $set:

Activity.update(
    { "_id": activityId, "usersActivities.userId": Meteor.userId() },
    {
        "$set": {
            'usersActivities.$.startDate': start,
            'usersActivities.$.endDate': end
        }
    }
)

So the positional $ operator here is what matches the "found index" from the array element and allows the $set operator to "change" the elements matched at that "position".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...