mongodb 字段检索_如何在MongoDB中创建,检索,更新和删除记录

news/2024/7/4 7:27:10

mongodb 字段检索

介绍 (Introduction)

MongoDB is a free and open-source NoSQL document database used commonly in modern web applications. In this short tutorial you’ll explore how to work with data in MongoDB. You’ll create, retrieve, update, and delete records.

MongoDB是一个免费的开源NoSQL文档数据库,通常在现代Web应用程序中使用。 在这个简短的教程中,您将探索如何在MongoDB中使用数据。 您将创建,检索,更新和删除记录。

先决条件 (Prerequisites)

To complete this tutorial you’ll need MongoDB installed, which you can do by following How To Install MongoDB on Ubuntu 18.04.

要完成本教程,您需要安装MongoDB,您可以按照如何在Ubuntu 18.04上安装MongoDB进行操作 。

创建数据库 (Creating a Database)

On the server running MongoDB, type mongo to open up a connection to the database:

在运行MongoDB的服务器上,键入mongo打开与数据库的连接:

  • mongo

    蒙哥

Once you see the > symbol, you’re ready to create your first database and start adding records.

看到>符号后,就可以创建第一个数据库并开始添加记录了。

Let’s create a personal database to store some data about users.

让我们创建一个个人数据库来存储有关用户的一些数据。

Our first command use userdb creates a new database with the name of “userdb” you can put whatever name you want in the format use <databasename> .

我们的第一个命令use userdb创建一个名为“ userdb”的新数据库,您可以use <databasename>格式输入任意名称。

  • use userdb

    使用userdb

You can verify the database you are currently using with the db command, which in our case returns “userdb”:

您可以使用db命令验证当前正在使用的db ,在本例中,该命令返回“ userdb”:

  • db

    D b

   
Output
userdb

Now that your database has been created, you can create some JSON-structured documents to store data in your database.

现在已经创建了数据库,您可以创建一些JSON结构的文档以将数据存储在数据库中。

Execute the following command to insert some data into your database:

执行以下命令以将一些数据插入数据库:

  • db.people.insert({ name: "Andrew", age: 33, hobbies: ["Coding", "Gaming", "Cooking"], hungry: false})

    db.people.insert({名称:“ Andrew”,年龄:33,兴趣爱好:[“ Coding”,“ Gaming”,“ Cooking”],饿了:false})

You’ll get the WriteResult notification letting you know your insertion was successful:

您将收到WriteResult通知,让您知道插入成功:


   
Output
WriteResult({ "nInserted" : 1 })

You can use many data-types, including strings, numbers, arrays, and boolean values. The Key doesn’t need to have the double quotation marks.

您可以使用许多数据类型,包括字符串,数字,数组和布尔值。 Key不需要带双引号。

检索数据 (Retrieving Data)

Once you have data in your collection, you can start to search and filter that data out using .find(<parameters>)

一旦您的集合中有数据,就可以开始使用.find(<parameters>)搜索和过滤该数据

To verify that your data has been added to the “people” document, use the find() syntax. Execute this command in the MongoDB console:

要验证您的数据已添加到“人员”文档中,请使用find()语法。 在MongoDB控制台中执行以下命令:

  • db.people.find()

    db.people.find()

This command shows all data that’s currently associated with the “people” document.

此命令显示当前与“人员”文档关联的所有数据。


   
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false }

If you want to turn this into pretty JSON format, use .pretty() after .find() :

如果要将其转换为漂亮的JSON格式,请在.pretty()之后使用.find()

  • db.people.find().pretty()

    db.people.find()。pretty()

   
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false }

When you add a new record, that Mongo will automatically create an _id key for you to reference at a later time.

当您添加新记录时,该Mongo会自动创建一个_id键供您以后参考。

Try to add more data and then we’ll work on modifying and searching the data.

尝试添加更多数据,然后我们将致力于修改和搜索数据。

  • db.people.insert({ name: "Riley", age: 3, hobbies: ["Sleeping", "Barking", "Snuggles"], hungry: true})

    db.people.insert({名称:“ Riley”,年龄:3,兴趣爱好:[“ Sleeping”,“ Barking”,“ Snuggles”],饥饿:true})
  • db.people.insert({ name: "You", age: 30, hobbies: ["Coding", "Reading DigitalOcean Articles", "Creating Droplets"], hungry: true})

    db.people.insert({名称:“您”,年龄:30,爱好:[“编码”,“阅读DigitalOcean文章”,“创建小滴”],饿了:true})

For instance, if I wanted to find only the records of those who are hungry:

例如,如果我只想查找饥饿者的记录:

  • db.people.find({ hungry: true }).pretty()

    db.people.find({hungry:true})。pretty()

   
Output
{ "_id" : ObjectId("5c08cbea3d828385a2162d95"), "name" : "Riley", "age" : 3, "hobbies" : [ "Sleeping", "Barking", "Snuggles" ], "hungry" : true } { "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "You", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets" ], "hungry" : true }

Or by specific hobbies:

或通过特定的爱好:

  • db.people.find({ hobbies: "Coding" }).pretty()

    db.people.find({爱好:“编码”})。pretty()

   
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false } { "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "You", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets" ], "hungry" : true }

更新数据 (Updating Data)

To modify your data, use the .update() function. but first let’s look at our data to see what we want to change:

要修改数据,请使用.update()函数。 但首先让我们看一下数据,看看我们要更改什么:

  • db.people.find().pretty()

    db.people.find()。pretty()

   
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false } { "_id" : ObjectId("5c08cbea3d828385a2162d95"), "name" : "Riley", "age" : 3, "hobbies" : [ "Sleeping", "Barking", "Snuggles" ], "hungry" : true } { "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "You", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets" ], "hungry" : true }

Modify the name of the third record like this:

修改第三条记录的名称,如下所示:

  • db.people.update({ name: "You"}, {$set: { name: "Sammy" }})

    db.people.update({name:“ You”},{$ set:{name:“ Sammy”}})

The first part of your statement specifies what you are searching for to update, and the second part is the new value you want to set. You’ll notice with this command, there was 1 record match, and 1 record modified:

语句的第一部分指定要搜索的内容以进行更新,第二部分是要设置的新值。 您会注意到,使用此命令,有1条记录匹配,并且1条记录已修改:


   
Output
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

If we now check that record with our newly set name:

如果现在使用我们新设置的名称检查该记录:

  • db.people.find({ name: "Sammy" }).pretty()

    db.people.find({name:“ Sammy”})。pretty()

   
Output
{ "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "Sammy", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets" ], "hungry" : true }

The name key value has been set to its new value of sammy.

name键值已设置为新值sammy

You can also push new hobbies to the array by using $push instead of $set :

您还可以通过使用$push而不是$set将新的爱好推送到数组中:

  • db.people.update({ name: "Sammy" }, {$push: { hobbies: "Typing furiously" }})

    db.people.update({name:“ Sammy”},{$ push:{业余爱好:“ Typingly furiously”}})
  • db.people.find({ name: "John" }).pretty()

    db.people.find({name:“ John”})。pretty()

   
Output
{ "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "John", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets", "Typing furiously" ], "hungry" : true }

Now let’s look at deleting data.

现在让我们看一下删除数据。

删除数据(D) (Deleting Data (D))

Remove data using the .remove() function. You can remove data in a couple ways, but the safest way is to locate a record to delete by using the unique _id so that, for instance, you have multiple “Sammy” entries, removing by the name: "Sammy" would remove all of them. Let’s try this:

使用.remove()函数删除数据。 您可以通过几种方法删除数据,但是最安全的方法是使用唯一的_id查找要删除的记录,例如,您有多个“ Sammy”条目,并通过name: "Sammy"删除name: "Sammy"将删除所有其中。 让我们尝试一下:

  • db.people.remove({ _id: ObjectId("5c08cc2e3d828385a2162d96")})

    db.people.remove({_id:ObjectId(“ 5c08cc2e3d828385a2162d96”)})

   
Output
WriteResult({ "nRemoved" : 1 })
  • db.people.find().pretty()

    db.people.find()。pretty()

   
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false } { "_id" : ObjectId("5c08cbea3d828385a2162d95"), "name" : "Riley", "age" : 3, "hobbies" : [ "Sleeping", "Barking", "Snuggles" ], "hungry" : true }

The “Sammy” entry has been removed safely, without affecting any other possible “Sammy” records if they were to exist. Try experimenting with this to see what else you can do.

“ Sammy”条目已安全删除,不会影响任何其他可能的“ Sammy”记录(如果存在)。 尝试进行此操作,看看还能做什么。

结论 (Conclusion)

After reading this article, you now have a basic understanding of how to create, retrieve, update, and delete records in a MongoDB database.

阅读本文之后,您现在对如何在MongoDB数据库中创建,检索,更新和删除记录有基本的了解。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-create-retrieve-update-and-delete-records-in-mongodb

mongodb 字段检索


http://www.niftyadmin.cn/n/3649453.html

相关文章

Java 集成开发环境——Eclipse JEE的安装和配置Tomcat

Eclipse是一个开放源代码的、基于Java的可扩展开发平台。就其本身而言&#xff0c;它只是一个框架和一组服务&#xff0c;用于通过插件组件构建开发环境。幸运的是&#xff0c;Eclipse 附带了一个标准的插件集&#xff0c;包括Java开发工具(Java Development Kit&#xff0c;JD…

Android Binder机制(超级详尽)

1&#xff0e;binder通信概述 binder通信是一种client-server的通信结构&#xff0c; 1.从表面上来看&#xff0c;是client通过获得一个server的代理接口&#xff0c;对server进行直接调用&#xff1b; 2.实际上&#xff0c;代理接口中定义的方法与server中定义的…

instagram架构_使用Facebook,Instagram和LinkedIn进行Django身份验证

instagram架构介绍 (Introduction) Manually signing up for and signing into accounts online can sometimes prove onerous. Modern web applications solve this through social authentication, which is primarily a way to allow users to sign in (and sign-up) with t…

[sip]SIP消息之逐项讲解 幻灯片

这是我编写的第四个针对SIP的幻灯片&#xff0c;实例讲述SIP消息中的各个字段&#xff0c;可用于Team内讲解并演示SIP协议的讲座。本讲义的版权归郑昀所有。允许拷贝、分发和在“GNU Free Documentation License”下的定制。对于关注SIP应用的你&#xff0c;任何的建议和修正都…

Windows 10安装Python-3.6.5

Python是一种跨平台的计算机程序设计语言。是一种面向对象的动态类型语言&#xff0c;最初被设计用于编写自动化脚本(shell)&#xff0c;随着版本的不断更新和语言新功能的添加&#xff0c;越多被用于独立的、大型项目的开发。 上学期学习了Python基础&#xff0c;觉得Python…

判断当前网络是否有网

public class CommonUtils {/** 检查是否有网络 */public static boolean isNetworkAvailable(Context context) {NetworkInfo info getNetworkInfo(context);if (info ! null) {return info.isAvailable();}return false;}/** 检查是否是WIFI */public static boolean isWifi…

beego静态页面设置_如何为静态GatsbyJS网站上的页面过渡设置动画

beego静态页面设置介绍 (Introduction) GatsbyJS is a React-based static site generator powered by GraphQL. It makes it possible for you to code and develop your site while Gatsby transforms it into a directory with a single HTML file with all your static ass…

Windows 10安装MySQL—5.6.4数据库

MySQL是一个关系型数据库管理系统&#xff0c;由瑞典MySQL AB公司开发&#xff0c;属于 Oracle旗下产品。MySQL 是最流行的关系型数据库管理系统之一&#xff0c;在 WEB 应用方面&#xff0c;MySQL是最好的 RDBMS(Relational Database Management System&#xff0c;关系数据库…