Home Database Mysql Tutorial mongodb数据库基本操作

mongodb数据库基本操作

Jun 07, 2016 pm 02:50 PM
mongo mongodb Basic operations database

一般来说,涉及到mongodb的操作主要有四种:增删查改。 nodejs可以很方便简洁的实现这些操作。 准备工作: ①、连接mongodb服务器 var SERVER = new mongodb.Server( 'localhost' , 27017 , {auto_reconnect: true }); 这里SERVER就指本地(localhost)的服

一般来说,涉及到mongodb的操作主要有四种:增删查改。

nodejs可以很方便简洁的实现这些操作。

准备工作:
①、连接mongodb服务器

<code class=" hljs cs"><span class="hljs-keyword">var</span> SERVER  = <span class="hljs-keyword">new</span> mongodb.Server(<span class="hljs-string">'localhost'</span>, <span class="hljs-number">27017</span>, {auto_reconnect:<span class="hljs-keyword">true</span>});</code>
Copy after login

这里SERVER就指本地(localhost)的服务器

②、连接服务器上的数据库

<code class=" hljs cs"><span class="hljs-keyword">var</span> DB = <span class="hljs-keyword">new</span> mongodb.Db(<span class="hljs-string">'users'</span>, SERVER, {safe:<span class="hljs-keyword">true</span>});</code>
Copy after login

SERVER指上面的数据库所在服务器,这里DB指SERVER上的user这个数据库。

③、打开数据库。
上面的连接好了以后,我们就可以打开数据库了。打开方式如下:

<code class=" hljs javascript">DB.open(<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(err, db)</span>{</span>
        <span class="hljs-keyword">if</span> (err) {
            <span class="hljs-comment">// throw err</span>
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-comment">// 打开成功, db就是打开的数据库,接下来“增删改查”的操作都对这个db来就可以了</span>
        }
}</code>
Copy after login

当然,我们一般不是直接对于一个数据库整体进行操作,而是针对其中的某一个collection来操作的,那么可以这样:

<code class=" hljs cs"><span class="hljs-keyword">var</span> Xcollection = db.collection(<span class="hljs-string">"userslist"</span>);</code>
Copy after login

这样Xcollection就指向了上面db数据库中的”userslist”这个collection了。

但是,如果是第一次使用这个collection,可以输入mongo命令创建一个名为“userslist”的collection,或者用如下的方法新建之并继续操作:

<code class=" hljs javascript">db.createCollection(<span class="hljs-string">'userslist'</span>, {safe:<span class="hljs-literal">true</span>}, <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(err, Xcollection)</span>{</span>
    <span class="hljs-comment">//同样在这里可以操作Xcollection,和上面意义是一样的。</span>
}</code>
Copy after login

使用db.createCollection(),如果该collection已存在,那么就仅仅是打开而已。

++++++++++++++++++++++++++++++++++++++++++
1、增
向collection中增加一个user对象(像{“a”:”b”}这种格式),可以这样来做:

<code class=" hljs javascript">collection.insert(user, {safe:<span class="hljs-literal">true</span>}, <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(err, result)</span>{</span>
    <span class="hljs-comment">// result是一个对象,表示插入数据的结果</span>
})</code>
Copy after login

2、查
在collection中,查询一个user对象可以这样来做:

<code class=" hljs javascript">collection.find(user).toArray(<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(err, items)</span> {</span>
    <span class="hljs-comment">//items是一个对象数组,从0开始编号,items.length表示查找到的对象个数</span>
})</code>
Copy after login

不过这里需要注意,查询出来的所有结果userX,并不一定是与user完全相等,只要userX中包含了user所有的键值对并且值都相等,那么userX就会被包含在items[]中。

3、改
待续

4、删
待续, too

诶,说的都是最浅显的内容了,更全面的还是看官方文档吧。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

MySQL: A User-Friendly Introduction to Databases MySQL: A User-Friendly Introduction to Databases Apr 10, 2025 am 09:27 AM

The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

See all articles