mongodb更新语句
MongoDB update is used to update document in a collection. In last tutorial, we learned about MongoDB insert with Mongo Shell and Java driver. Today we will look into MongoDB update and different options provided by Mongo Shell and Java driver.
MongoDB更新用于更新集合中的文档。 在上一教程中,我们了解了如何使用Mongo Shell和Java驱动程序插入MongoDB 。 今天,我们将研究MongoDB更新以及Mongo Shell和Java驱动程序提供的不同选项。
MongoDB更新 (MongoDB update)
MongoDB shell client update syntax is:
MongoDB Shell客户端更新语法为:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
First parameter in MongoDB update is query that gives us the target rows – for example {country:"USA"}
to get all documents where country is USA and {country:{$ne:"USA"}}
to get all the documents where country is not USA.
MongoDB更新中的第一个参数是查询,该查询为我们提供了目标行–例如, {country:"USA"}
获取所有国家(美国)的文档,而{country:{$ne:"USA"}}
获取所有国家的文档。国家不是美国。
Second parameter in MongoDB update is used to define the list of fields to update, for example we can use {name:"Pankaj Updated"}
to update the name.
MongoDB update中的第二个参数用于定义要更新的字段列表,例如,我们可以使用{name:"Pankaj Updated"}
来更新名称。
Other options in MongoDB update are optional but important too;
MongoDB更新中的其他选项是可选的,但也很重要。
- if upsert is specified as true then update query will insert a document if there are no matches to the query, default value is false. 如果将upsert指定为true,则更新查询将在查询不匹配的情况下插入文档,默认值为false。
- if multi is specified as true then all the documents that matches the query criteria will be updated, default value is false. 如果将multi指定为true,则将更新所有符合查询条件的文档,默认值为false。
- writeConcern can be used to specify write concern, if not provided default write concern will be used. writeConcern可用于指定写关注,如果未提供,将使用默认写关注。
MongoDB更新文档运算符 (MongoDB Update Document Operators)
We have many mongo update parameter operators available – most widely used are $set, $inc, $currentDate.
我们有许多mongo更新参数运算符可用-最广泛使用的是$ set,$ inc,$ currentDate。
Name | Description |
---|---|
$inc | Increments the value of the field by the specified amount. |
$mul | Multiplies the value of the field by the specified amount. |
$rename | Renames a field. |
$setOnInsert | Sets the value of a field upon document creation during an upsert. Has no effect on update operations that modify existing documents. |
$set | Sets the value of a field in a document. |
$unset | Removes the specified field from a document. |
$min | Only updates the field if the specified value is less than the existing field value. |
$max | Only updates the field if the specified value is greater than the existing field value. |
$currentDate | Sets the value of a field to current date, either as a Date or a Timestamp. |
名称 | 描述 |
---|---|
$ inc | 将字段的值增加指定的数量。 |
$ mul | 将字段的值乘以指定的数量。 |
$重命名 | 重命名字段。 |
$ setOnInsert | 在upsert过程中,在创建文档时设置字段的值。 对修改现有文档的更新操作没有影响。 |
$ set | 设置文档中字段的值。 |
$未设定 | 从文档中删除指定的字段。 |
$ min | 仅当指定值小于现有字段值时才更新该字段。 |
最高$ | 仅当指定值大于现有字段值时才更新该字段。 |
$ currentDate | 将字段的值设置为当前日期,即日期或时间戳。 |
We will look into some of these in next sections.
我们将在下一部分中研究其中的一些。
Few important points to note with MongoDB update operations are:
MongoDB更新操作要注意的几个要点是:
- If <update> document contains update operators then it must contain only update operator expressions and only corresponding fields will be updated. 如果<update>文档包含更新运算符,则它必须仅包含更新运算符表达式,并且仅将更新相应的字段。
- If the <update> document contains only field:value expressions then it will replace the query matching document (except _id) and we can’t update multiple documents with this (make sense, it will have duplicate data). 如果<update>文档仅包含field:value表达式,则它将替换查询匹配的文档(_id除外),并且我们不能以此来更新多个文档(有意义的是,它将具有重复的数据)。
- If upsert is true and no document matches the query criteria, update() inserts a single document. The update creates the new document with either:
The fields and values of the <update> parameter or the fields and values of both <query> and <update> parameters if the <update> parameter contains only update operator expressions. The update creates a base document from the equality clauses in the <query> parameter, and then applies the update expressions from the <update> parameter.
<update>参数的字段和值,或者<query>和<update>参数的字段和值(如果<update>参数仅包含更新运算符表达式) 。 此更新通过<query>参数中的equals子句创建基础文档,然后从<update>参数应用更新表达式。
MongoDB更新文档示例 (MongoDB Update Document Example)
Now let’s see some of the MongoDB update example using Mongo shell.
现在,让我们来看一些使用Mongo Shell的MongoDB更新示例。
MongoDB更新单个文档中的单个字段 (MongoDB Update single field in a single document)
> db.Persons.drop() true > db.Persons.insert([ ... {_id:123,name:"Pankaj",country:"USA"}, ... {_id:456,name:"David",country:"USA"}, ... {_id:789,name:"Lisa",country:"India"}] ... ) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.Persons.update({name:"Pankaj"},{$set: {country:"India"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.Persons.find() { "_id" : 123, "name" : "Pankaj", "country" : "India" } { "_id" : 456, "name" : "David", "country" : "USA" } { "_id" : 789, "name" : "Lisa", "country" : "India" } >
Notice that I am using
$set
operator to update a field value, if we don’t use that it will replace the whole document, as shown below. We can use it to replace all the fields in a particular document.> db.Persons.drop() true > db.Persons.insert([ ... {_id:123,name:"Pankaj",country:"USA"}, ... {_id:456,name:"David",country:"USA"}, ... {_id:789,name:"Lisa",country:"India"}] ... ) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.Persons.update({name:"Pankaj"},{$set: {country:"India"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.Persons.find() { "_id" : 123, "name" : "Pankaj", "country" : "India" } { "_id" : 456, "name" : "David", "country" : "USA" } { "_id" : 789, "name" : "Lisa", "country" : "India" } >
请注意,我使用
$set
运算符更新字段值,如果不使用它将替换整个文档,如下所示。 我们可以使用它来替换特定文档中的所有字段。MongoDB更新多个字段 (MongoDB Update multiple fields)
Notice that $set is used with JSON data, so if you want multiple fields to set then we can pass them as JSON.
> db.Persons.update({name:"David"},{$set: {country:"India",name:"David New"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.Persons.find() { "_id" : 123, "country" : "India" } { "_id" : 456, "name" : "David New", "country" : "India" } { "_id" : 789, "name" : "Lisa", "country" : "India" } >
请注意,$ set与JSON数据一起使用,因此,如果要设置多个字段,则可以将它们作为JSON传递。
MongoDB更新–添加新字段 (MongoDB Update – Add a new field)
We can use
$set
operator to add a new field to the document too, as shown below.> db.Persons.drop() true > db.Persons.insert([ {_id:123,name:"Pankaj",country:"USA"}, {_id:456,name:"David",country:"USA"}, {_id:789,name:"Lisa",country:"India"}]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.Persons.update({_id:123},{$set: {city: "San Jose"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.Persons.find({_id:123}) { "_id" : 123, "name" : "Pankaj", "country" : "USA", "city" : "San Jose" } >
我们也可以使用
$set
运算符向文档中添加一个新字段,如下所示。MongoDB更新子文档 (MongoDB Update subdocument)
We can use mongo update dot operator to update values in a MongoDB subdocument, it’s very similar to java syntax to access methods and variables.
> db.Persons.insert({_id:100,name:"Pankaj",address:{city:"San Jose",country:"USA"}}) WriteResult({ "nInserted" : 1 }) > db.Persons.update({_id:100},{$set: {"address.city": "Santa Clara"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.Persons.find({_id:100}) { "_id" : 100, "name" : "Pankaj", "address" : { "city" : "Santa Clara", "country" : "USA" } } >
Notice the use of double quote for key, if double/single quote is not used then it will throw error message as
SyntaxError: Unexpected token .
.我们可以使用mongo update点运算符来更新MongoDB子文档中的值,这与访问方法和变量的Java语法非常相似。
请注意,密钥使用了双引号,如果未使用双引号/单引号,则会将错误消息作为
SyntaxError: Unexpected token .
抛出SyntaxError: Unexpected token .
。MongoDB更新–删除字段 (MongoDB Update – Remove a field)
We can use MongoDB update
$unset
operator to remove a field from the document.> db.Persons.find({_id:123}) { "_id" : 123, "name" : "Pankaj", "country" : "USA", "city" : "San Jose" } > db.Persons.update({_id:123},{$unset: {city: ""}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.Persons.find({_id:123}) { "_id" : 123, "name" : "Pankaj", "country" : "USA" } >
我们可以使用MongoDB update
$unset
运算符从文档中删除一个字段。MongoDB更新–如果找不到匹配项,请插入新文档 (MongoDB Update – Insert a new document if no match found)
> db.Persons.update({name:"Pankaj"},{$set: {country:"India"}},{upsert: true}) WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : ObjectId("53fe495bcc59ebd19e1adebb") }) > db.Persons.find() { "_id" : ObjectId("53fe495bcc59ebd19e1adebb"), "name" : "Pankaj", "country" : "India" } >
MongoDB更新多个文档 (MongoDB Update multiple documents)
> db.Persons.insert([{name:"Pankaj",salary:5000}, {name:"David",salary:10000}, {name:"Lisa",salary:8000}] ) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.Persons.update({salary: {$lt:9000}},{$inc: {salary: 1000}},{multi:true}) WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) > db.Persons.find() { "_id" : ObjectId("53fe49f7b1e38e3716f79117"), "name" : "Pankaj", "salary" : 6000 } { "_id" : ObjectId("53fe49f7b1e38e3716f79118"), "name" : "David", "salary" : 10000 } { "_id" : ObjectId("53fe49f7b1e38e3716f79119"), "name" : "Lisa", "salary" : 9000 } >
Above update() has incremented the salary by 1000 for every document where salary is less than 9000.
对于每个少于9000的文档,上述update()方法将每个文档的薪水增加1000。
使用Java驱动程序的MongoDB更新文档示例 (MongoDB update document example using Java Driver)
We looked into different MongoDB document update example using Mongo Shell. Now let’s look at some of the examples using MongoDB java driver.
我们使用Mongo Shell研究了不同的MongoDB文档更新示例。 现在,让我们来看一些使用MongoDB Java驱动程序的示例。
MongoDB更新Java驱动程序–更新单个文档中的单列 (MongoDB Update Java Driver – Update Single Column in a single document)
Below program shows you how to use $set in java program to make sure you are updating a single matching document.
For simplicity, test data before and after update is added as comments in the program itself.
MongoDBUpdateExample.java
package com.journaldev.mongodb.main; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; public class MongoDBUpdateExample { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); DBCollection col = db.getCollection("Persons"); /** * Test Data - Before update * > db.Persons.find() { "_id" : 123, "name" : "Pankaj", "country" : "USA" } { "_id" : 456, "name" : "David", "country" : "USA" } { "_id" : 789, "name" : "Lisa", "country" : "India" } > */ //Update single field in a single document DBObject query = new BasicDBObject("name", "Pankaj"); DBObject update = new BasicDBObject(); update.put("$set", new BasicDBObject("country","India")); WriteResult result = col.update(query, update); /** * Test Data - After update * > db.Persons.find() { "_id" : 123, "name" : "Pankaj", "country" : "India" } { "_id" : 456, "name" : "David", "country" : "USA" } { "_id" : 789, "name" : "Lisa", "country" : "India" } > */ mongo.close(); } }
下面的程序显示了如何在Java程序中使用$ set来确保更新单个匹配的文档。
为简单起见,将更新前后的测试数据作为注释添加到程序本身中。
MongoDBUpdateExample.java
MongoDB更新Java驱动程序–更新多列 (MongoDB Update Java Driver – Update multiple columns)
We can add multiple fields in the MongoDB Update Document to update multiple columns in a single document.
package com.journaldev.mongodb.main; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; public class MongoDBUpdateExample { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); DBCollection col = db.getCollection("Persons"); /** * Test Data - Before update * > db.Persons.find() { "_id" : 123, "name" : "Pankaj", "country" : "India" } { "_id" : 456, "name" : "David", "country" : "USA" } { "_id" : 789, "name" : "Lisa", "country" : "India" } > */ //Update multiple field in a single document DBObject query = new BasicDBObject("name", "David"); DBObject update = new BasicDBObject(); update.put("$set", new BasicDBObject("country","India").append("name", "David New")); WriteResult result = col.update(query, update); /** * Test Data - After update * > db.Persons.find() { "_id" : 123, "name" : "Pankaj", "country" : "India" } { "_id" : 456, "name" : "David New", "country" : "India" } { "_id" : 789, "name" : "Lisa", "country" : "India" } > */ mongo.close(); } }
我们可以在MongoDB更新文档中添加多个字段,以更新单个文档中的多个列。
MongoDB Update Java驱动程序–在单个文档中添加新字段 (MongoDB Update Java Driver – Add a new field in a single document)
Again we can use $set to add a new field in MongoDB document using update query.
package com.journaldev.mongodb.main; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; public class MongoDBUpdateExample { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); DBCollection col = db.getCollection("Persons"); /** * Test Data - Before update * > db.Persons.find() { "_id" : 123, "name" : "Pankaj", "country" : "India" } { "_id" : 456, "name" : "David New", "country" : "India" } { "_id" : 789, "name" : "Lisa", "country" : "India" } > */ //Add a new field in a single document DBObject query = new BasicDBObject("_id", 123); DBObject update = new BasicDBObject(); update.put("$set", new BasicDBObject("city","San Jose")); WriteResult result = col.update(query, update); /** * Test Data - After update * > db.Persons.find() { "_id" : 123, "name" : "Pankaj", "country" : "India", "city" : "San Jose" } { "_id" : 456, "name" : "David New", "country" : "India" } { "_id" : 789, "name" : "Lisa", "country" : "India" } > */ mongo.close(); } }
同样,我们可以使用$ set通过更新查询在MongoDB文档中添加新字段。
MongoDB更新Java驱动程序–更新子文档 (MongoDB Update Java Driver – Update subdocument)
Just like shell commands, we can use dot operator with $set to update sub-documents using update query.
package com.journaldev.mongodb.main; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; public class MongoDBUpdateExample { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); DBCollection col = db.getCollection("Persons"); /** * Test Data - Before update * > db.Persons.find() { "_id" : 100, "name" : "Pankaj", "address" : { "city" : "San Jose", "country" : "USA" } } > */ //Update sub-document in a single document DBObject query = new BasicDBObject("_id", 100); DBObject update = new BasicDBObject(); update.put("$set", new BasicDBObject("address.city","Santa Clara")); WriteResult result = col.update(query, update); /** * Test Data - After update * > db.Persons.find() { "_id" : 100, "name" : "Pankaj", "address" : { "city" : "Santa Clara", "country" : "USA" } } > */ mongo.close(); } }
就像shell命令一样,我们可以使用点运算符和$ set一起使用更新查询来更新子文档。
MongoDB更新Java驱动程序–删除字段 (MongoDB Update Java Driver – Remove a field)
We use $unset update option to remove a field from MongoDB document, we can remove fields from subdocument too.
package com.journaldev.mongodb.main; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; public class MongoDBUpdateExample { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); DBCollection col = db.getCollection("Persons"); /** * Test Data - Before update * > db.Persons.find() { "_id" : 100, "name" : "Pankaj", "address" : { "city" : "Santa Clara", "country" : "USA" } } > */ //Remove a field in a single document DBObject query = new BasicDBObject("_id", 100); DBObject update = new BasicDBObject(); update.put("$unset", new BasicDBObject("address.city","")); WriteResult result = col.update(query, update); /** * Test Data - After update * > db.Persons.find() { "_id" : 100, "name" : "Pankaj", "address" : { "country" : "USA" } } > */ mongo.close(); } }
我们使用$ unset update选项从MongoDB文档中删除字段,我们也可以从子文档中删除字段。
MongoDB Update Java驱动程序–如果找不到匹配项,请插入新文档 (MongoDB Update Java Driver – Insert a new document if no match found)
We need to pass upsert parameter value as true for this, an example is shown below.
package com.journaldev.mongodb.main; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; public class MongoDBUpdateExample { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); DBCollection col = db.getCollection("Persons"); /** * Test Data - Before update * > db.Persons.find() { "_id" : 100, "name" : "Pankaj", "address" : { "country" : "USA" } } > */ //insert document if no match found DBObject query = new BasicDBObject("name", "Lisa"); DBObject update = new BasicDBObject(); update.put("$set", new BasicDBObject("city","San Jose")); WriteResult result = col.update(query, update, true, false); /** * Test Data - After update * > db.Persons.find() { "_id" : 100, "name" : "Pankaj", "address" : { "country" : "USA" } } { "_id" : ObjectId("54020800cc59ebd19e1adebc"), "name" : "Lisa", "city" : "San Jose" } > */ mongo.close(); } }
为此,我们需要将upsert参数值传递为true ,如下所示。
MongoDB更新Java驱动程序–更新多个文档 (MongoDB Update Java Driver – Update multiple documents)
MongoDB Java Driver API provides updateMulti method that we can use to update multiple documents, in below example we are updating all the documents salary by 1000 where it’s less than 9000. This is also one of the example of
$inc
update option.package com.journaldev.mongodb.main; import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; public class MongoDBUpdateExample { public static void main(String[] args) throws UnknownHostException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); DBCollection col = db.getCollection("Persons"); /** * Test Data - Before update * > db.Persons.find() { "_id" : ObjectId("5402088bb1e38e3716f7911a"), "name" : "Pankaj", "salary" : 5000 } { "_id" : ObjectId("5402088bb1e38e3716f7911b"), "name" : "David", "salary" : 10000 } { "_id" : ObjectId("5402088bb1e38e3716f7911c"), "name" : "Lisa", "salary" : 8000 } > */ //Update multiple document - $inc example DBObject query = new BasicDBObject("salary", new BasicDBObject("$lt", 9000)); DBObject update = new BasicDBObject(); update.put("$inc", new BasicDBObject("salary",1000)); WriteResult result = col.updateMulti(query, update); /** * Test Data - After update * > db.Persons.find() { "_id" : ObjectId("5402088bb1e38e3716f7911a"), "name" : "Pankaj", "salary" : 6000 } { "_id" : ObjectId("5402088bb1e38e3716f7911b"), "name" : "David", "salary" : 10000 } { "_id" : ObjectId("5402088bb1e38e3716f7911c"), "name" : "Lisa", "salary" : 9000 } > */ mongo.close(); } }
MongoDB Java驱动程序API提供了updateMulti方法,可用于更新多个文档,在下面的示例中,我们将所有文档的薪水更新为1000(小于9000)。这也是
$inc
update选项的示例之一。
That’s all for MongoDB Update document examples using Mongo shell as well as MongoDB java driver, do let me know if you face any problems with it.
这就是使用Mongo Shell和MongoDB Java驱动程序的MongoDB Update文档示例的全部内容,如果您遇到任何问题,请告诉我。
mongodb更新语句