mongodb quick references for update queries

Assume in the users collection there are documents such as this one.

{
    id: 2,
    name: "Amy",
    email: "amy@gmail.com",
    age:"22",
    profession:"writer",
    interests: ["writing", "watch tv", "travel"],
    address: {
    	zip: 10016,
    	state: "NY"
    }
}

Set the name to “Emma” and age to 23 for the document with id equals to 2.

db.users.update({id:2}, {"$set": {"name": "Emma", "age":23}});

Add “running” to the interests of the document with id equals to 2. The $addToSet operator will add the new interest “running”, it will do nothing if “running” is already in the interests array.

db.users.update({id:2}, {"$addToSet": {"interests": "running"}});

Add “running” to the interests for all the documents in the users collections. The difference is the first parameter is an empty object so it will find all documents, and there is a thrid parameter which specifys multi is true meaning apply the changes in the second document to all matched documents specified by the first parameter.

db.users.update({},{"$addToSet": {"interests": "running"}}, {"multi":true});

Remove “running” from the interests for all documents in the users collections.

db.users.update({},{"$pull": {"interests": "running"}}, {"multi":true});

Add a new field “country” equals to “US” to all documents in the users collection.

db.users.update({}, {"$set": {"country":"US"}}, {"multi":true});

Remove the field “country” from all docuemts in the users collection.

db.users.update({},{"$unset": {"country":""}}, {"multi":true});

Update the embeded field zip to 12202 in the address field for document with id equals to 2.

db.users.update({id:2}, {"$set": {"address.zip":12202}});

Search within Codexpedia

Custom Search

Search the entire web

Custom Search