Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Connect to MongoDB

Node.js Connect to MongoDB

MongoDB is a document-oriented database management system written in C++.

In this chapter we will introduce how to use Node.js to connect to MongoDB and perform operations on the database.

If you do not yet have basic knowledge of MongoDB, you can refer to our tutorial:MongoDB Tutorial。

Install the Driver

This tutorial usesthe Taobao customized cnpm commandto install:



$ cnpm install mongodb

After a successful installation, we can use the MongoClient object to connect to the database:

Example

const

{

MongoClient

}

=

require

(

'mongodb'

)

;

async

function

main

(

)

{

   

// MongoDB connection URI

   

const

uri

=

"mongodb://localhost:27017"

;

// If you are using a remote MongoDB, change the URI accordingly

   

// Create a new MongoClient

   

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

   

try

{

       

// Connect to the MongoDB server

        await client.

connect

(

)

;

        console.

log

(

"Connected successfully to server"

)

;

     

   

}

finally

{

       

// Make sure to close the connection when done

        await client.

close

(

)

;

   

}

}

main

(

)

.

catch

(

console.

error

)

;

The output of the code above is:

Connected successfully to server

Connection parameter description:

Next we will implement the CRUD (create, read, update, delete) functionality.


Create the database

To create a database in MongoDB, first we need to create a MongoClient object, then configure the specified URL and port number.

If the database does not exist, MongoDB will create the database and establish a connection.

Create a Connection

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Database operations can be performed here, such as creating collections or inserting documents

const

collection

=

database

.

collection

(

'

exampleCollection

'

)

;

const

doc

=

{

name

:

"

Example

"

,

type

:

"

Test

"

}

;

const

result

=

await

collection

.

insertOne

(

doc

)

;

console

.

log

(

`New document created,

ID

with id: $

{

result

.

insertedId

}

`

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

The output of the code above is:

成功连接到服务器

新文档已创建,ID 为: 6678e18e0bb3f4247be610d8


Create a collection

We can use the createCollection() method to create a collection:

Create a collection

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create a new document

const

doc

=

{

name

:

"

Example

"

,

type

:

"

Test

"

}

;

//

Insert the document into the collection

const

result

=

await

collection

.

insertOne

(

doc

)

;

console

.

log

(

`New document created,

ID

with id: $

{

result

.

insertedId

}

`

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

The output of the code above is:

成功连接到服务器

集合 exampleCollection 创建成功

新文档已创建,ID 为: 6678e1b5c742b3ebd57f9759


Database Operations ( CURD )

Unlike MySQL, MongoDB automatically creates databases and collections, so we do not need to create them manually before use.

Insert data

In the following example we connect to the exampleCollection table of the runoob database and insert a record using insertOne():

Insert one document

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create a new document

const

doc

=

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

;

//

Insert the document into the collection

const

result

=

await

collection

.

insertOne

(

doc

)

;

console

.

log

(

`New document created,

ID

with id: $

{

result

.

insertedId

}

`

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

Executing the following command produces this result:



成功连接到服务器

集合 exampleCollection 创建成功

新文档已创建,ID 为: 6678e1d1f9503dc2e0e2a20b

From the output, the data was inserted successfully.

We can also open the MongoDB client to view the data, for example:



> show dbs

runoob  0.000GB          # 创建了 runoob 数据库



> use runoob             # 切换到 runoob 数据库



runoob> show tables

exampleCollection        # 创建了 exampleCollection 集合(数据表)

                    # Automatically created the site collection (data table)

runoob> db.exampleCollection.find()

[

  {

    _id: ObjectId('6678e1d1f9503dc2e0e2a20b'),

    name: 'Alice',

    age: 25,

    address: 'Wonderland'

  }

]

To insert multiple records you can use insertMany():

Insert multiple documents

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

key

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

result

.

insertedIds

[

key

]

}

`

)

;

}

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

The execution output is:

成功连接到服务器

集合 exampleCollection 创建成功

3 个新文档已创建,ID 为:

文档 1: 6678e30e80ac30e5e689f13a

文档 2: 6678e30e80ac30e5e689f13b

文档 3: 6678e30e80ac30e5e689f13c

Query data

You can use find() to look up data; find() can return all data matching the conditions. If no conditions are specified, find() returns all data in the collection.

find()

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Query all documents in the collection

const

query

=

{

}

;

//

An empty query object means query all documents

const

options

=

{

projection

:

{

_id

:

0

,

name

:

1

,

age

:

1

,

address

:

1

}

}

;

//

Select only the required fields

const

cursor

=

collection

.

find

(

query

,

options

)

;

//

Print all queried documents

const

allValues

=

await

cursor

.

toArray

(

)

;

console

.

log

(

"

Queried documents:

"

)

;

console

.

log

(

allValues

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

The execution output is:

成功连接到服务器

集合 exampleCollection 创建成功

3 个新文档已创建,ID 为:

文档 1: 0

文档 2: 1

文档 3: 2

Documents found:

[

  { name: 'Alice', age: 25, address: 'Wonderland' },

  { name: 'Bob', age: 30, address: 'Builderland' },

  { name: 'Charlie', age: 35, address: 'Chocolate Factory' }

]

The following example retrieves the instance whose name is "Alice":

Query data with specified conditions

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Query documents using the name parameter

const

query

=

{

name

:

"

Alice

"

}

;

//

Search condition

const

options

=

{

projection

:

{

_id

:

0

,

name

:

1

,

age

:

1

,

address

:

1

}

}

;

//

Select only the required fields

const

cursor

=

collection

.

find

(

query

,

options

)

;

//

Print the queried documents

const

allValues

=

await

cursor

.

toArray

(

)

;

console

.

log

(

"

Queried documents:

"

)

;

console

.

log

(

allValues

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

Executing the following command produces this result:



成功连接到服务器

集合 exampleCollection 创建成功

3 个新文档已创建,ID 为:

文档 1: 0

文档 2: 1

文档 3: 2

Documents found:

[

  { name: 'Alice', age: 25, address: 'Wonderland' }

]

Update data

We can also modify data in the database; the following example modifies the data whose name is "Alice":

Update one document

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Specify the condition and update the data based on the name parameter

const

filter

=

{

name

:

"

Alice

"

}

;

//

Search condition

const

updateDoc

=

{

$

set

:

{

age

:

28

,

address

:

"

New Wonderland

"

}

,

}

;

const

updateResult

=

await

collection

.

updateOne

(

filter

,

updateDoc

)

;

console

.

log

(

`$

{

updateResult

.

matchedCount

}

documents matched the filter`

)

;

console

.

log

(

`$

{

updateResult

.

modifiedCount

}

documents updated`

)

;

//

Query the updated document

const

updatedDocument

=

await

collection

.

findOne

(

filter

)

;

console

.

log

(

"

Updated document:

"

)

;

console

.

log

(

updatedDocument

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

After successful execution, the output is as follows:



成功连接到服务器

集合 exampleCollection 创建成功

3 个新文档已创建,ID 为:

文档 1: 0

文档 2: 1

文档 3: 2

1 个文档匹配筛选条件

1 个文档已更新

Updated documentation:

{

  _id: new ObjectId('6678e1d1f9503dc2e0e2a20b'),

  name: 'Alice',

  age: 28,

  address: 'New Wonderland'

}

To update all documents matching the condition you can use updateMany():

Update multiple documents

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Alice

"

,

age

:

28

,

address

:

"

Old Wonderland

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Specify the condition and update multiple documents based on the name parameter

const

filter

=

{

name

:

"

Alice

"

}

;

//

Search condition

const

updateDoc

=

{

$

set

:

{

address

:

"

Updated Wonderland

"

}

,

}

;

const

updateResult

=

await

collection

.

updateMany

(

filter

,

updateDoc

)

;

console

.

log

(

`$

{

updateResult

.

matchedCount

}

documents matched the filter`

)

;

console

.

log

(

`$

{

updateResult

.

modifiedCount

}

documents updated`

)

;

//

Query the updated document

const

updatedDocuments

=

await

collection

.

find

(

filter

)

.

toArray

(

)

;

console

.

log

(

"

Updated document:

"

)

;

console

.

log

(

updatedDocuments

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

Delete data

The following example deletes the data whose name is "Alice" :

Delete one document

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Specify the condition and delete one document based on the name parameter

const

filter

=

{

name

:

"

Alice

"

}

;

//

Search condition

const

deleteResult

=

await

collection

.

deleteOne

(

filter

)

;

console

.

log

(

`$

{

deleteResult

.

deletedCount

}

document deleted`

)

;

//

Query all documents in the collection to confirm the deletion

const

remainingDocuments

=

await

collection

.

find

(

{

}

)

.

toArray

(

)

;

console

.

log

(

"

Remaining documents:

"

)

;

console

.

log

(

remainingDocuments

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

After successful execution, the output is:



成功连接到服务器

集合 exampleCollection 创建成功

3 个新文档已创建,ID 为:

文档 1: 0

文档 2: 1

文档 3: 2

1 个文档已删除

Remaining documents:

[

  {

    _id: new ObjectId('6678e18e0bb3f4247be610d8'),

    name: 'Example',

    type: 'Test'

  },

...

To delete multiple records you can use the deleteMany() method

The following example deletes all data whose type is en :

Delete multiple documents

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Alice

"

,

age

:

28

,

address

:

"

Old Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Specify the condition and delete multiple documents based on the name parameter

const

filter

=

{

name

:

"

Alice

"

}

;

//

Search condition

const

deleteResult

=

await

collection

.

deleteMany

(

filter

)

;

console

.

log

(

`$

{

deleteResult

.

deletedCount

}

document deleted`

)

;

//

Query all documents in the collection to confirm the deletion

const

remainingDocuments

=

await

collection

.

find

(

{

}

)

.

toArray

(

)

;

console

.

log

(

"

Remaining documents:

"

)

;

console

.

log

(

remainingDocuments

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

Sorting

Sorting Use the sort() method, which accepts one parameter specifying ascending (1) or descending (-1) order.

For example:

{ type: 1 }  // 按 type 字段升序

{ type: -1 } // 按 type 字段降序

Sort by type in ascending order:

Sorting

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

,

{

name

:

"

Dave

"

,

age

:

20

,

address

:

"

Dreamland

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Sort documents using the sort() method

//

Sort by the age field in ascending order

const

sortedDocsAsc

=

await

collection

.

find

(

)

.

sort

(

{

age

:

1

}

)

.

toArray

(

)

;

console

.

log

(

"

Documents sorted by the age field in ascending order:

"

)

;

console

.

log

(

sortedDocsAsc

)

;

//

Sort by the age field in descending order

const

sortedDocsDesc

=

await

collection

.

find

(

)

.

sort

(

{

age

: -

1

}

)

.

toArray

(

)

;

console

.

log

(

"

Documents sorted by the age field in descending order:

"

)

;

console

.

log

(

sortedDocsDesc

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

Query Pagination

To set a specified number of returned records you can use the limit() method, which accepts only one parameter specifying the number of records to return.

limit(): read two records

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

,

{

name

:

"

Dave

"

,

age

:

20

,

address

:

"

Dreamland

"

}

,

{

name

:

"

Eve

"

,

age

:

22

,

address

:

"

Eden

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Use the limit() method to limit the number of query results

const

limitedDocs

=

await

collection

.

find

(

)

.

limit

(

3

)

.

toArray

(

)

;

console

.

log

(

"

Limit the query results to 3 documents:

"

)

;

console

.

log

(

limitedDocs

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

To specify the number of records to skip, you can use the skip() method.

The skip() method is used to skip a specified number of documents and return the query results of the remaining documents.

skip(): skip the first two records and read two records

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

runoob

'

)

;

//

Create a collection using the createCollection method

const

collectionName

=

'

exampleCollection

'

;

await

database

.

createCollection

(

collectionName

)

;

console

.

log

(

`Collection $

{

collectionName

}

created successfully`

)

;

//

Get a collection

const

collection

=

database

.

collection

(

collectionName

)

;

//

Create multiple new documents

const

docs

=

[

{

name

:

"

Alice

"

,

age

:

25

,

address

:

"

Wonderland

"

}

,

{

name

:

"

Bob

"

,

age

:

30

,

address

:

"

Builderland

"

}

,

{

name

:

"

Charlie

"

,

age

:

35

,

address

:

"

Chocolate Factory

"

}

,

{

name

:

"

Dave

"

,

age

:

20

,

address

:

"

Dreamland

"

}

,

{

name

:

"

Eve

"

,

age

:

22

,

address

:

"

Eden

"

}

]

;

//

Insert multiple documents into the collection

const

result

=

await

collection

.

insertMany

(

docs

)

;

console

.

log

(

`$

{

result

.

insertedCount

}

new documents created,

ID

with ids:`

)

;

Object

.

keys

(

result

.

insertedIds

)

.

forEach

(

(

id

,

index

)

=>

{

console

.

log

(

`Document $

{

index

1

}

: $

{

id

}

`

)

;

}

)

;

//

Use the skip() method to skip the first two documents and return the remaining documents

const

skippedDocs

=

await

collection

.

find

(

)

.

skip

(

2

)

.

toArray

(

)

;

console

.

log

(

"

Query results after skipping the first two documents:

"

)

;

console

.

log

(

skippedDocs

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

Join Operations

MongoDB is not a relational database, but we can use $lookup to implement a left join.

$lookup is an aggregation pipeline operator in MongoDB used to perform a left outer join. It can be used to look up in one collection documents that match conditions in another collection and merge them together.

For example, suppose we have two collections of data:

Collection 1: orders

[

  { "_id": 1, "product_id": 101, "quantity": 2 },

  { "_id": 2, "product_id": 102, "quantity": 1 },

  { "_id": 3, "product_id": 103, "quantity": 4 }

]

Collection 2: products

[

  { "_id": 101, "name": "Product A", "price": 50 },

  { "_id": 102, "name": "Product B", "price": 70 },

  { "_id": 103, "name": "Product C", "price": 100 },

  { "_id": 104, "name": "Product D", "price": 120 }

]

Now we want to use the $lookup operation to associate the product_id field in the orders collection with the _id field in the products collection, to obtain detailed product information for each order.

The following is a MongoDB aggregation example showing how to implement this functionality:

Example

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

async

function

main

(

)

{

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

try

{

//

Connect to the MongoDB server

await

client

.

connect

(

)

;

console

.

log

(

"

Successfully connected to the server

"

)

;

//

Specify the database

const

database

=

client

.

db

(

'

mydatabase

'

)

;

//

orders collection

const

ordersCollection

=

database

.

collection

(

'

orders

'

)

;

//

products collection

const

productsCollection

=

database

.

collection

(

'

products

'

)

;

//

Define the aggregation pipeline, using $lookup to perform a left outer join

const

pipeline

=

[

{

$

lookup

:

{

from

:

'

products

'

,

//

The name of the collection to join

localField

:

'

product_id

'

,

//

The field in the local collection used for joining

foreignField

:

'

_id

'

,

//

The field in the joined collection used for joining

as

:

'

productDetails

'

//

The name of the field to include in the output result

}

}

]

;

//

Execute the aggregation operation

const

result

=

await

ordersCollection

.

aggregate

(

pipeline

)

.

toArray

(

)

;

//

Output the query results

console

.

log

(

"

Left outer join query results:

"

)

;

console

.

log

(

result

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

main

(

)

.

catch

(

console

.

error

)

;

Delete a collection

We can use the drop() method to delete a collection:

drop()

var

MongoClient

=

require

(

'

mongodb

'

)

.

MongoClient

;

var

url

=

"

mongodb://localhost:27017/

"

;

MongoClient

.

connect

(

url

,

function

(

err

,

db

)

{

if

(

err

)

throw

err

;

var

dbo

=

db

.

db

(

"

runoob

"

)

;

//

Delete the test collection

dbo

.

collection

(

"

test

"

)

.

drop

(

function

(

err

,

delOK

)

{

//

If successful, delOK returns true, otherwise it returns false

if

(

err

)

throw

err

;

if

(

delOK

)

console

.

log

(

"

Collection deleted

"

)

;

db

.

close

(

)

;

}

)

;

}

)

;


Using Promises

Promise is a class provided by ECMAScript 6, intended for writing complex asynchronous tasks more elegantly.

If you do not yet understand Promises, you can refer to JavaScript Promise。

The following example uses a Promise to create a collection:

Example

const

{

MongoClient

}

=

require

(

'

mongodb

'

)

;

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

//

Use a Promise to wrap the process of connecting to the database

function

connectDB

(

)

{

return

new

Promise

(

(

resolve

,

reject

)

=>

{

//

Connect to the MongoDB server

client

.

connect

(

(

err

)

=>

{

if

(

err

)

{

reject

(

err

)

;

}

else

{

console

.

log

(

"

Successfully connected to the MongoDB server

"

)

;

resolve

(

client

.

db

(

)

)

;

//

Return the database instance

}

}

)

;

}

)

;

}

//

Usage examples

connectDB

(

)

.

then

(

database

=>

{

//

Database operations can continue here

console

.

log

(

"

Connected to the database successfully

"

)

;

//

Example: output the database name

console

.

log

(

"

Database name:

"

,

database

.

databaseName

)

;

//

If other operations are needed, you can continue writing code here

//

such as querying, inserting documents, etc.

//

Finally, close the connection

client

.

close

(

)

;

}

)

.

catch

(

err

=>

{

console

.

error

(

"

Error occurred while connecting to the database:

"

,

err

)

;

}

)

;

Promise Data Operations

Now we will implement four consecutive operations in one program: add, query, update, delete.

Example

const

{

MongoClient

,

ObjectId

}

=

require

(

'

mongodb

'

)

;

//

MongoDB connection URI

const

uri

=

"

mongodb://localhost:27017

"

;

//

Modify it according to your MongoDB server address

//

Create a new MongoClient

const

client

=

new

MongoClient

(

uri

,

{

useNewUrlParser

:

true

,

useUnifiedTopology

:

true

}

)

;

//

Use a Promise to wrap the process of connecting to the database

function

connectDB

(

)

{

return

new

Promise

(

(

resolve

,

reject

)

=>

{

//

Connect to the MongoDB server

client

.

connect

(

(

err

)

=>

{

if

(

err

)

{

reject

(

err

)

;

}

else

{

console

.

log

(

"

Successfully connected to the MongoDB server

"

)

;

resolve

(

client

.

db

(

)

)

;

//

Return the database instance

}

}

)

;

}

)

;

}

//

Function to add a document

function

insertDocument

(

db

,

document

)

{

const

collection

=

db

.

collection

(

'

documents

'

)

;

return

new

Promise

(

(

resolve

,

reject

)

=>

{

collection

.

insertOne

(

document

,

(

err

,

result

)

=>

{

if

(

err

)

{

reject

(

err

)

;

}

else

{

console

.

log

(

"

Document added successfully

"

)

;

resolve

(

result

)

;

}

}

)

;

}

)

;

}

//

Function to query documents

function

findDocuments

(

db

)

{

const

collection

=

db

.

collection

(

'

documents

'

)

;

return

new

Promise

(

(

resolve

,

reject

)

=>

{

collection

.

find

(

{

}

)

.

toArray

(

(

err

,

docs

)

=>

{

if

(

err

)

{

reject

(

err

)

;

}

else

{

console

.

log

(

"

Document query result:

"

)

;

console

.

log

(

docs

)

;

resolve

(

docs

)

;

}

}

)

;

}

)

;

}

//

Function to update a document

function

updateDocument

(

db

,

id

,

updatedValues

)

{

const

collection

=

db

.

collection

(

'

documents

'

)

;

return

new

Promise

(

(

resolve

,

reject

)

=>

{

collection

.

updateOne

(

{

_id

:

ObjectId

(

id

)

}

,

{

$

set

:

updatedValues

}

,

(

err

,

result

)

=>

{

if

(

err

)

{

reject

(

err

)

;

}

else

{

console

.

log

(

"

Document updated successfully

"

)

;

resolve

(

result

)

;

}

}

)

;

}

)

;

}

//

Function to delete a document

function

deleteDocument

(

db

,

id

)

{

const

collection

=

db

.

collection

(

'

documents

'

)

;

return

new

Promise

(

(

resolve

,

reject

)

=>

{

collection

.

deleteOne

(

{

_id

:

ObjectId

(

id

)

}

,

(

err

,

result

)

=>

{

if

(

err

)

{

reject

(

err

)

;

}

else

{

console

.

log

(

"

Document deleted successfully

"

)

;

resolve

(

result

)

;

}

}

)

;

}

)

;

}

//

Usage example: consecutively perform the add, query, update, and delete operations

async

function

performOperations

(

)

{

try

{

const

database

=

await

connectDB

(

)

;

//

Add a document

const

insertResult

=

await

insertDocument

(

database

,

{

name

:

"

Document 1

"

}

)

;

//

Query documents

const

findResult

=

await

findDocuments

(

database

)

;

//

Update documents

const

updatedDocId

=

insertResult

.

insertedId

;

//

Update using the ID returned from inserting the document

const

updateResult

=

await

updateDocument

(

database

,

updatedDocId

,

{

name

:

"

Updated Document 1

"

}

)

;

//

Delete documents

const

deleteResult

=

await

deleteDocument

(

database

,

updatedDocId

)

;

//

Output the operation result

console

.

log

(

"

All operations completed:

"

)

;

console

.

log

(

"

Document deletion result:

"

,

deleteResult

)

;

}

catch

(

err

)

{

console

.

error

(

"

Error occurred while performing the operation:

"

,

err

)

;

}

finally

{

//

Make sure to close the connection when done

await

client

.

close

(

)

;

}

}

//

Perform the operation

performOperations

(

)

;

Execution result:

数据库已连接

[ { _id: 5f1664966833e531d83d3ac6, site: 'runoob.com' } ]

[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]

[]