MongoDB findAndModify() 示例
MongoDB findAndModify() 方法根据输入的选择条件修改并返回单个文档。默认情况下,返回的文档不显示更新的内容。如果数据库中不存在符合条件的记录,则在 upsert 设置为 true 的情况下将插入一条新记录。
MongoDB findAndModify()
mongodb findAndModify 方法的语法如下。
db.collection.findAndModify({
query: <document>,
sort: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>
})
参数说明如下。query:定义需要修改哪条记录的选择条件。sort:当选择条件检索到多个文档时,确定要修改哪个文档。new:表示显示修改后的文档。fields:指定要返回的字段集。upsert:如果选择条件无法检索到文档,则创建新文档。
MongoDB findAndModify 重点
使用 findAndModify MongoDB 调用时需要注意以下几点:
- 如果输入的选择条件未获取任何文档并且 upsert 设置为 true,则插入指定的值并创建一个新文档。
- 如果在执行更新或删除操作时输入的选择条件未获取任何文档,则返回的输出为空。
- 如果新选项设置为 false 并且未提及排序操作,则返回的输出为空。
- 如果新选项设置为 false 并且指定了排序操作,则输出为空。
MongoDB findAndModify 示例
现在让我们看一些示例,演示 findAndModify API 的用法。首先,让我们创建一些测试数据。我们将通过 mongo 控制台创建一个新的汽车文档,其中包含名称、颜色、汽车编号 (cno)、速度和制造国 (mfdcountry) 字段。
db.car.insert(
[
{ _id: 1, name: "Alto", color: "Red",cno: "H410",speed:40,mfdcountry: "India"},
{ _id: 2, name: "Polo", color: "White",cno: "H411",speed:45,mfdcountry: "Japan" },
{ _id: 3, name: "Audi", color: "Black",cno: "H412",speed:50,mfdcountry: "Germany" }
]
)
现在让我们使用mongodb find验证数据是否确实插入:
db.car.find()
{ "_id" : 1, "name" : "Alto", "color" : "Red", "cno" : "H410", "speed" : 40, "mfdcountry" : "India" }
{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
接下来我们来看一下 find 和 modified 的实际用法,我们描述了不同的可能性。案例 1:文档存在于数据库中
db.car.findAndModify({
query: { name: "Alto" },
sort: { cno: 1 },
update: { $inc: { speed: 10 } },
})
- 查询在汽车集合中找到一个名称字段的值为 Alto 的文档。
- 排序将查询结果按升序排列。如果有多个文档符合查询条件,则该方法将选择按此排序的第一个文档进行修改。
- 更新将速度字段的值增加 10。
- 该方法返回为此更新选择的原始文档:
输出:
{
"_id" : 1,
"name" : "Alto",
"color" : "Red",
"cno" : "H410",
"speed" : 40,
"mfdcountry" : "India"
}
情况 2:将新选项设置为 true(返回更新后的数据集)
db.car.findAndModify({
query: { name: "HondaCity", color: "Silver", cno:"H415" ,speed: 25 },
sort: { cno: 1 },
update: { $inc: { speed: 20 } },
upsert: true,
new: true
})
输出:
{
"_id" : ObjectId("546c9f347256eabc40c9da1c"),
"cno" : "H415",
"color" : "Silver",
"name" : "HondaCity",
"speed" : 45
}
请注意,速度显示为 45,这是因为我们将 new 设置为 true 后更新的值。如果未设置,速度字段将显示为 20,即旧值,尽管它在数据库中已更新。情况 3:upsert 设置为 true
db.car.findAndModify({
query: { name: "WagonR" },
sort: { cno: 1 },
update: { $inc: { speed: 5 } },
upsert: <strong>true</strong>
})
输出:
db.car.find();
{ "_id" : 1, "name" : "Alto", "color" : "Red", "cno" : "H410", "speed" : 50, "mfdcountry" : "India" }
{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
{ "_id" : ObjectId("546c7c7d6be0faf69ee36546"), "name" : "WagonR", "speed" : 5 }
The car name with WagonR is not in the db hence a new document is created in database. The method returns an empty document { } if the sort option is specified. If sort option is not included then the method returns null. Apart from these, this can also be used for doing a Sort and Remove operation. If the remove field is set to true, the car name with the specified criteria will be removed from the database.
db.car.findAndModify(
{
query: { name: "Alto" },
sort: { cno: 1 },
remove: true
}
)
Output:
{
"_id" : 1,
"name" : "Alto",
"color" : "Red",
"cno" : "H410",
"speed" : 50,
"mfdcountry" : "India"
}
The remove field is set to true the document with the name “Alto” gets deleted from the database.
MongoDB findAndModify Java Example
The operations depicted above is all manual performed using mongo shell. The same can be done programmatically in Java as below. Download the mongo driver jar and add it to your classpath. First, we need to establish a connection to the mongodb server using the Mongo client. The name of the database should be specified for the connection as a parameter. If the database does not exists, a new database will is created. After this, we will add a few records into the database and do a findAndModify operation and then verify if the records are actually updated. Below program works with mongo java driver versions 2.x.
package com.journaldev.mongodb;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
public class MongoDBFindAndModify {
public static void main(String[] args) throws UnknownHostException {
// Get a new connection to the db assuming it is running.
MongoClient mongoClient = new MongoClient("localhost");
// use test as the database. Use your database here.
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("car");
// insert some test data to start with.
BasicDBObject obj = new BasicDBObject();
obj.append("name", "Volkswagen");
obj.append("color", "JetBlue");
obj.append("cno", "H672");
obj.append("speed", 62);
obj.append("mfdcountry", "Italy");
coll.insert(obj);
// findAndModify operation. Update colour to blue for cars having speed
// < 45
DBObject query = new BasicDBObject("speed",
new BasicDBObject("$lt", 45));
DBObject update = new BasicDBObject();
update.put("$set", new BasicDBObject("color", "Blue"));
DBCursor cursor = coll.find();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
coll.findAndModify(query, update);
}
}
Output:
//Test Data Before Insert
{ "_id" : 2.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "speed" : 45.0 , "mfdcountry" : "Japan"}
{ "_id" : 3.0 , "name" : "Audi" , "color" : "Black" , "cno" : "H412" , "speed" : 50.0 , "mfdcountry" : "Germany"}
//Test Data After insert
{ "_id" : 2.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "speed" : 45.0 , "mfdcountry" : "Japan"}
{ "_id" : 3.0 , "name" : "Audi" , "color" : "Black" , "cno" : "H412" , "speed" : 50.0 , "mfdcountry" : "Germany"}
{ "_id" : { "$oid" : "546cc76093f404729e2e946e"} , "name" : "Volkswagen" , "color" : "JetBlue" , "cno" : "H672" , "speed" : 62 , "mfdcountry" : "Italy"}
/*Test Data Before findandModify
{ "_id" : 2.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "speed" : 45.0 , "mfdcountry" : "Japan"}
{ "_id" : 3.0 , "name" : "Audi" , "color" : "Black" , "cno" : "H412" , "speed" : 50.0 , "mfdcountry" : "Germany"}
{ "_id" : { "$oid" : "546cc76093f404729e2e946e"} , "name" : "Volkswagen" , "color" : "JetBlue" , "cno" : "H672" , "speed" : 62 , "mfdcountry" : "Italy"}
{ "_id" : { "$oid" : "546c7c7d6be0faf69ee36546"} , "name" : "WagonR" , "speed" : 5.0}
/*Test Data After findAndModify
{ "_id" : 2.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "speed" : 45.0 , "mfdcountry" : "Japan"}
{ "_id" : 3.0 , "name" : "Audi" , "color" : "Black" , "cno" : "H412" , "speed" : 50.0 , "mfdcountry" : "Germany"}
{ "_id" : { "$oid" : "546cc76093f404729e2e946e"} , "name" : "Volkswagen" , "color" : "JetBlue" , "cno" : "H672" , "speed" : 62 , "mfdcountry" : "Italy"}
{ "_id" : { "$oid" : "546c7c7d6be0faf69ee36546"} , "name" : "WagonR" , "speed" : 5.0 , "color" : "Blue"}
If you are using MongoDB java driver versions 3.x, then use below program.
package com.journaldev.mongodb.main;
import java.net.UnknownHostException;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBFindAndModify {
public static void main(String[] args) throws UnknownHostException {
// Get a new connection to the db assuming it is running.
MongoClient mongoClient = new MongoClient("localhost");
// use test as the database. Use your database here.
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> coll = db.getCollection("car");
// insert some test data to start with.
Document obj = new Document();
obj.append("name", "Volkswagen");
obj.append("color", "JetBlue");
obj.append("cno", "H672");
obj.append("speed", 62);
obj.append("mfdcountry", "Italy");
coll.insertOne(obj);
// findAndModify operation. Update color to blue for cars having speed > 45
Bson query = new Document("speed",
new Document("$gt", 45));
Bson update = new Document("$set",
new Document("color", "Blue"));
System.out.println("before update");
findAndPrint(coll);
coll.findOneAndUpdate(query, update);
System.out.println("after update of color field");
findAndPrint(coll);
mongoClient.close();
}
private static void findAndPrint(MongoCollection<Document> coll) {
FindIterable<Document> cursor = coll.find();
for (Document d : cursor)
System.out.println(d);
}
}
Below image shows the output of above program, notice the change in color field. That’s all for MongoDB findAndModify example, we will look into more MongoDB operations in the coming posts. Reference: MongoDB Official Documentation