SoFunction
Updated on 2025-03-10

Mongodb usage example

Install mongodb module npm install --save mongodb

Database connection

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

//Connect the test databasevar url = 'mongodb://localhost:27017/test';
(url, (err,db) => {
 (null,err);
 ('Connected successfully');
 ();
});

Insert data

Insert a document object

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

//Path to test databasevar url = 'mongodb://localhost:27017/test';

//Insert the documentvar insertDocument = (db,callback) => {
 //Add json document to the blog collection under the test library ('blog').insertOne({
  name:"xiaos",
  age:22
 }, (err, result) => {
  (err,null);
  ('New document was successfully added');
  callback();
 });
};

 
//Insert operation(url, (err,db) => {
 (null,err);
 insertDocument(db, ()=>{
  ();
 });
});

Batch insert operation: insertMany(doc, options, callback) (if there is no callback function, it returns a Promise object itself)

Simple insertMany operation

var MongoClient = require('mongodb').MongoClient,
 test = require('assert');

('mongodb://localhost:27017/test',(err, db) => {
 var blog = ('blog');
 //Add two new document objects ([{name:"shen"},{name:"fzq"}],(err,r) => {
  (null,err);
  //The r returned in the callback function is the object that has completed the insertion operation, and the insertedCount property is the number of objects that have been inserted.  (2,);
  ();
 });
}); 

Use Promise's batch insert operation!

var MongoClient = require('mongodb').MongoClient,
 test = require('assert');
('mongodb://localhost:27017/test', (err,db) => {
 var blog = ('blog');
 ([{name:"xiaosGG"},{name:"fzqDD"}]).then((r) => {
  (2,);
  ();
 });
});

Because mongodb and nodejs are both asynchronous io mechanisms, almost all time-consuming operations are completed in the form of callback functions. However, because the callback function hierarchy is nested, a piece of code may follow a large piece of }); as the level increases, the code becomes difficult to understand and maintain. When using MongoDB, it is recommended to use Promise to solve the problem of callback nesting.

As can be seen from the above code, insertMany([obj...]) returns a Promise object. We use .then((r)=>{}) to receive the normal callback value and use .catch((err) =>{}) to grab the exception.

Batch insert operation using generator (Generator)

var MongoClient = require('mongodb').MongoClient,
 test = require('assert'),
 co = require('co');
 
co(function*(){
 var db = yield ('mongodb://localhost:27017/test');
 var blog = ('blog');
 var r = yield ([{name:"xiaosBB"},{name:"fzqMM"}]);
 (2,);
 ();
});

Single document insertion:insertOne(doc, options, callback) (If there is no callback function, it returns a Promise object itself)

Simple insertion operation

var MongoClient = require('mongodb').MongoClient,
 test = require('assert');
('mongodb://localhost:27017/test',(err,db)=>{
 var blog = ('blog');
 ({name:"xiaos"},(err,r) => {
  (null,err);
  (1,);
  ();
 });
});

Insert operation using Promise

var MongoClient = require('mongodb').MongoClient,
 test = require('assert');
('mongodb://localhost:27017/test',(err,db)=>{
 var blog = ('blog');
 ({name:"xiaos"}).then((r)=>{
  (1,);
  ();
 });
});

Insert operation using generator

var MongoClient = require('mongodb').MongoClient,
 test = require('assert'),
 co = require('co');
 
co(function*(){
 var db = yield ('mongodb://localhost:27017/test');
 var blog = ('blog');
 var r = yield ({name:"xiaosBB"});
 (1,);
 ();
});

mapReduce(map,reduce,options,callback) return Promise if no callback

var MongoClient = require('mongodb').MongoClient,
 test = require('assert');

()

isCapped(callback) return Promise if no callback

var MongoClient = require('mongodb').MongoClient,
 test = require('assert');
('mongodb://localhost:27017/test',(err,db) => {
 ('newBlog',{'capped':true,'size':1024},(err,collection) => {
  ('newBlog',);  
  ((err,capped) => {
   (true,capped);
   ();
  });
 });
});

Capped collection refers to a fixed-size collection. After inserting a new element, the old element will be overwritten, keeping the size of the entire collection unchanged.

//Enter mongo in the command line//Create a 1024 size myCappedCollection collection('myCappedCollection',{'capped':true,'size':1024});
//Insert 1000 recordsfor (var i = 1;i <= 1000;i++){
 ({id:i,name:'xiaos'+i});
}
//Query the number of documents()
//In fact, only18Documentsidfor983-1000 That is, the new element covers the old element

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.