Add a new property to a document in MongoDB

This is an example of adding a new property based on another collection. In this case, I have two collections users and posts and I need to add a new property to posts that I also added to users

In this example, I have a users collection that looks like

user: {  
    _id: 1,
    facebookId: 12345
}

and a posts collection that looks like:

post: {  
    _id: 123,
    userId: 1,
    content: 'blah'
}

My goal is to add the facebookId property to all posts based on the users. I was able to accomplish this via the following command in mongo shell:

db.posts.forEach(function(post) {  
  var user = db.users.findOne({ _id: post.userId })
    , facebookId = (user && user.facebookId) ? user.facebookId : null;

  db.posts.update({ _id: post._id}
    , { $set: { facebookId: facebookId}}
    , false
    , false);  
  });
});

This does the following:
1. Creates a cursor for each record in the posts collection.
2. Attempts to find the associated user for the post.
3. Sets the facebookId to the user's facebookId property, or sets it to null if the associated user was not found (just covering our bases here).
4. Updates the post document by setting the facebookId property (note this uses the < 2.2 syntax for updates).

comments powered by Disqus