mongodb示例_MongoDB findAndModify()示例

mongodb示例

MongoDB findAndModify() method modifies and returns a single document based upon the selection criteria entered. The returned document does not show the updated content by default. If the records matching the criteria does not exist in the database, a new record will be inserted if the upsert is set to true.

MongoDB的findAndModify()方法根据输入的选择条件修改并返回单个文档。 默认情况下,返回的文档不显示更新的内容。 如果数据库中不存在符合条件的记录,则将upsert设置为true时将插入一条新记录。

MongoDB findAndModify() (MongoDB findAndModify())

The syntax for mongodb findAndModify method is as follows.

mongodb findAndModify方法的语法如下。

db.collection.findAndModify({
    query: <document>,
    sort: <document>,
    new: <boolean>,
    fields: <document>,
    upsert: <boolean>
})

The description of the parameters are as follows.

参数说明如下。

query: Defines the selection criteria as to which record needs modification.

query :定义关于哪些记录需要修改的选择标准。

sort: Determines which document should be modified when the selection criteria retrieves multiple documents.

sort :确定选择标准检索多个文档时应修改的文档。

new: indicates that the modified document will be displayed.

new :表示将显示修改后的文档。

fields: specifies the set of fields to be returned.

fields :指定要返回的字段集。

upsert: creates a new document if the selection criteria fails to retrieve a document.

upsert :如果选择标准无法检索文档,则创建一个新文档。

MongoDB findAndModify重要点 (MongoDB findAndModify important points)

Some of the things to keep in mind while using the findAndModify MongoDB calls are:

使用findAndModify MongoDB调用时要记住的一些事情是:

  • If the entered selection criteria does not fetch any document and if upsert is set to true, then the specified values are inserted and a new document is created.

    如果输入的选择标准未获取任何文档,并且upsert设置为true,则将插入指定的值并创建一个新文档。
  • If the entered selection criteria does not fetch any document while performing update or remove operations, the output returned is null.

    如果在执行更新或删除操作时输入的选择条件未获取任何文档,则返回的输出为null。
  • If the new option is set to false and sort operation is not mentioned, the output returned is null.

    如果将new选项设置为false并且未提及排序操作,则返回的输出为null。
  • If the new option is set to false and sort operation is specified, the output is empty.

    如果将新选项设置为false并指定了排序操作,则输出为空。

MongoDB findAndModify示例 (MongoDB findAndModify Example)

Now let us see some examples demonstrating the usage of the findAndModify API.

现在,让我们看一些示例,这些示例演示findAndModify API的用法。

First, let us create some test data to start with.

首先,让我们创建一些测试数据。

We will create a new car document with name, color, car no (cno), speed and manufactured country(mfdcountry) fields through the mongo console.

我们将通过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" }
]
)

Let us now verify that the data was actually inserted using mongodb find :

现在让我们验证是否使用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" }

Moving on to the actual usage of find and modify, we depict different possibilities.

继续查找和修改的实际用法,我们描述了各种可能性。

Case 1: The document exists in the database

情况1:该文档存在于数据库中

db.car.findAndModify({
query: { name: "Alto" },
sort: { cno: 1 },
update: { $inc: { speed: 10 } },
})
  1. The query finds a document in the car collection where the name field has the value Alto.

    该查询在汽车收藏夹中找到一个文档,其中名称字段的值为Alto。
  2. The sort orders the results of the query in ascending order. If multiple documents meet the query condition, the method will select for modification the first document as ordered by this sort.

    排序以升序对查询结果进行排序。 如果多个文档满足查询条件,则该方法将按照这种排序的顺序选择第一个文档进行修改。
  3. The update increments the value of the speed field by 10.

    此更新将速度字段的值增加10。
  4. The method returns the original document selected for this update :

    该方法返回为此更新选择的原始文档:

Output:

输出:

{
"_id" : 1,
"name" : "Alto",
"color" : "Red",
"cno" : "H410",
"speed" : 40,
"mfdcountry" : "India"
}

Case 2: The new option set to true (returns the updated data set)

情况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
})

Output:

输出:

{
"_id" : ObjectId("546c9f347256eabc40c9da1c"),
"cno" : "H415",
"color" : "Silver",
"name" : "HondaCity",
"speed" : 45
}

Note that speed is being displayed as 45 which is the updated value since we set new to be true. If this is not set, the speed field will be shown as 20 , the old value though it gets updated in the database.

请注意,由于我们将new设置为true,所以速度显示为更新值45。 如果未设置,则速度字段将显示为20,尽管旧值在数据库中已更新。

Case 3: The upsert is set to true

情况3:upsert设置为true

db.car.findAndModify({
query: { name: "WagonR" },
sort: { cno: 1 },
update: { $inc: { speed: 5 } },
upsert: <strong>true</strong>
})

Output:

输出:

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.

WagonR的汽车名称不在数据库中,因此在数据库中创建了一个新文档。 如果指定了排序选项,该方法将返回一个空文档{}。 如果不包括sort选项,则该方法返回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.

如果删除字段设置为true,则具有指定条件的汽车名称将从数据库中删除。

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.

remove字段设置为true,名称为“ Alto”​​的文档将从数据库中删除。

MongoDB findAndModify Java示例 (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.

上面描述的操作都是使用mongo shell手动执行的。 可以在Java中以编程方式完成以下操作。

Download the mongo driver jar and add it to your classpath.

下载mongo驱动程序jar并将其添加到您的类路径中。

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.

首先,我们需要使用Mongo客户端建立与mongodb服务器的连接。 应该为连接指定数据库名称作为参数。 如果数据库不存在,将创建一个新数据库。

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.

此后,我们将一些记录添加到数据库中并执行findAndModify操作,然后验证记录是否实际更新。

Below program works with mongo java driver versions 2.x.

下面的程序适用于mongo java驱动程序版本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.

如果您使用的是MongoDB Java驱动程序版本3.x,请使用以下程序。

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.

这就是MongoDB findAndModify示例的全部内容,我们将在以后的文章中研究更多MongoDB操作。

Reference: MongoDB Official Documentation

参考: MongoDB官方文档

翻译自: https://www.journaldev.com/6221/mongodb-findandmodify-example

mongodb示例

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值