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// < 45DBObject 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 > 45Bson 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示例

mongodb示例_MongoDB findAndModify()示例相关推荐

  1. mongoDB 入门指南、示例

    http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html mongoDB 入门指南.示例 上一篇:简单介绍mongoDB 一.准备工作 ...

  2. [MongoDB] Java异步操作Mongo示例

    [MongoDB] Java异步操作Mongo示例 一.问题描述 二.版本说明 1.数据库 2.JDK版本 3.依赖 三.相关代码 1.ObservableSubscriber.java和Consum ...

  3. mongodb教程_MongoDB教程

    mongodb教程 Welcome to the MongoDB tutorial index post. MongoDB is one of the most widely used NoSQL d ...

  4. ajax 示例_通过示例了解挥发

    ajax 示例 我们已经花了几个月的时间来稳定Plumbr中的锁定检测功能 . 在此期间,我们遇到了许多棘手的并发问题. 许多问题是独特的,但是一种特殊类型的问题一直反复出现. 您可能已经猜到了–滥用 ...

  5. 11. shell当中read详解,read语法选项,read用法示例,脚本示例,while read line详解,掌握原则

    shell当中read详解,read语法选项,read用法示例,脚本示例,while read line详解,掌握原则 文章目录 1.1 read详解 1.2 用法示例 1.3 while read ...

  6. 锐浪报表 VFP9 全示例文件,示例所用锐浪版本号为 6.8.22.1201

    锐浪报表 VFP9 全示例文件,示例所用锐浪版本号为 6.8.22.1201 原文地址: https://mp.weixin.qq.com/s/jY0WiDlpi-sFfFJVuipUIQ 被人安利了 ...

  7. Node JS和MongoDB的集成简单示例

    In this post, we will discuss about how to integration Node JS Platform with MongoDB NoSQL Database ...

  8. python读取sqlserver的数据_Python实现读取SQLServer数据并插入到MongoDB数据库的方法示例...

    本文实例讲述了Python实现读取SQLServer数据并插入到MongoDB数据库的方法.分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import pyodbc ...

  9. python批量读取图片并批量保存_Python实现批量读取图片并存入mongodb数据库的方法示例...

    本文实例讲述了Python实现批量读取图片并存入mongodb数据库的方法.分享给大家供大家参考,具体如下: 我的图片放在E:\image\中,然后使用python将图片读取然后,显示一张,存入取一张 ...

最新文章

  1. AI一眼识别这是什么鸟 “我们来找茬”十级选手诞生
  2. Intel Realsense 通过用户配置文件(profile)获取深度传感器(depth_sensor)超蛋疼的一幕 dir()
  3. SpringBoot底层注解-@ImportResource导入Spring配置文件
  4. mysql explain using_[MySQL] explain中的using where和using index
  5. Trident State译文
  6. 如何使用Native Messaging API 打开window程序
  7. DCMTK DCMSCU例子
  8. 视频动作检测最新发展调研(Action Detection)
  9. Golang 方法接收者为值与指针的区别
  10. PRD 如何编写好的需求文档
  11. java松鼠大战代码_松鼠大战2金手指版
  12. c均值聚类matlab,实现代码 - 模糊C均值聚类算法(原理+Matlab代码)
  13. 电信跨域跨系统业务实践
  14. Python好酷|allpairspy一款高效的正交实验法生成用例工具
  15. [从头读历史] 第276节 诗经 陈风
  16. DNX 版本升级命令
  17. Pixel2Mesh-Tensorflow2
  18. 前端高频面试题-场景题
  19. 显示透明的PNG图片
  20. 多益2018春招前端技术面试

热门文章

  1. vimnbsp;自动识别UTF8和GB2312
  2. phpmyadmin安全预防
  3. 洛谷——P1155 双栈排序
  4. const的理解、const指针、指向const的指针
  5. 简单的二维数组问题,不用不知道,一用吓一跳
  6. 【★原创★】夜晚,不要让电白白流失!
  7. 使用EDITPLUS编写C#控制台应用程序
  8. 不能显示隐藏文件的问题
  9. .dll与.lib文件的区别
  10. 人之间的尊重是相互的_人与人之间,尊重很重要