Update query in MongoDB shell

2020-02-19 04:25发布

问题:

In the shell, my query is:

db.checkin_4e95ae0926abe9ad28000001.update({location_city:"New York"}, {location_country: "FUDGE!"});

However, it doesn't actually update my records. It doesn't error either. When I do a db.checkin_4e95ae0926abe9ad28000001.find({location_city:"New York"}); after running this, I get all my results but the location_country has not changed:

{
    "_id": ObjectId("4e970209a0290b70660009e9"),
    "addedOn": ISODate("2011-10-13T15:21:45.772Z"),
    "location_address1": "",
    "location_city": "New York",
    "location_country": "United States",
    "location_latLong": {
        "xLon": -74.007124,
        "yLat": 40.71455
    },
    "location_source": "socialprofile",
    "location_state": "New York",
    "location_zip": ""
}

回答1:

Changed in version 3.6. Following is the syntax for update :

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

Example :

db.getCollection('products').update({},{$unset: {translate:1, qordoba_translation_version:1}}, {multi: true})

In your example :

db.checkin_4e95ae0926abe9ad28000001.update(
   {location_city:"New York"}, //query
   // $update query
   { $set : { location_country: "FUDGE!"}});

By default, the update() method updates a single document. Set the Multi Parameter to update all documents that match the query criteria.

Example 2 :

   db.checkin_4e95ae0926abe9ad28000001.update(
       {location_city:"New York"}, //query
       // $update query
       { $set : { location_country: "FUDGE!"}}, {multi: true});


回答2:

This is because in second parameter of update function you need to use $set operator to update location_country as in example below:

db.checkin_4e95ae0926abe9ad28000001.update(
   {location_city:"New York"}, //find criteria
   // this row contains fix with $set oper
   { $set : { location_country: "FUDGE!"}}); 

Here you can find a list of available update operators.



回答3:

db.m_country.update(
    {"countryId": "962a0935-bf3d-4f63-a53c-254760273ede"}, 
    {$set: {'countryPopulation': '12540000'}})