Addition, deletion, modification and query of mongodb database (with picture and demo)

Noun exegesis

In the screenshot below, some terms need to be explained for ease of understanding and application:

  • cuckoo is called the library name, that is, the name of the database
  • users is called the collection name, that is, the name of the colony
  • Right band_ Rows of IDS are called documents
  • And_ ID, username and password are called fields
  • To summarize: Database > Collection > document > Field

increase

Add a piece of data to the collection

Now the data with collection as users is as follows:

Now let's turn it into the following data:

method:

db.collection('users').insertOne({hello: "world"}, function(err, data) {
	if(err) {
		console.log(err);
	} else {
		console.log(data);
	}
})
// If you do not need to return data, function may not be written
Add multiple pieces of data to the collection

Now turn the above example into this:

method:

db.collection('users')
  .insertMany([{one: 'Article 1 data'}, {two: 'Article 2 data'}], (err, data) => {
     if(err) {
       console.log(err);
     } else {
       console.log(data);
     }
   })
 // Similarly, if you do not need to return data, the following err data function may not be written

Note: the original save() method is obsolete. The new methods after version 3.2 are introduced now

Delete

Delete a single document

raw data:

Now delete the "first data" document in the original data and it will become as follows:

Practice:

db.collection('users')
            .deleteOne({one: "Article 1 data"}, (err, data) => {
              if(err) {
                console.log(err);
              }else {
                console.log(data);
              }
            })
Delete multiple documents containing certain data at the same time

Direct write method:

// Delete all documents with one: "first data"
db.collection('users')
            .deleteMany({one: "Article 1 data"}], (err, data) => {
              if(err) {
                console.log(err);
              }else {
                console.log(data);
              }
            })
Delete all documents in the collection
db.collection('users').deleteMany({});

Note: the original remove() method is obsolete.

Change (update)

  • Introducing operators
$set: // Update data
Update a piece of data in the document

raw data:

Now, change the value of one in the document to "dilireba":

db.collection('users').updateOne({one: 'hello'}, {
	$set: {one: "dilireba"}
})
Update multiple pieces of data in the document

Now, change the value of one in the document to "dilireba":

db.collection('users').updateMany({one: 'hello'}, {
	$set: {one: "dilireba"}
})
Update a piece of data in the document and add data

Now, change the value of one in the document to "dilireba", and add an age data "age": 18

db.collection('users').updateOne({one: 'hello'}, {
	$set: {one: "dilireba", age: 18}
})
Delete a piece of data when updating


Now, delete the data "two:" world ":

db.collection('users').update({two: 'world'}, {
	$unset: {two: ''}
})

Update of nested data

The processing of nested data is relatively complex, so it is issued separately.

Add data to nested arrays

raw data:

The task here is an array. Now add objects and fields to it. Make the data like this:

Practice:

db.collection('users').updateOne({username: "222"}, {
	$addToSet: {
		task: {
			date: new Date().getTime(),
			newTask: [],
			onGoing: [],
			finished: [],
			abandoned: []
		}
	}
})

// Note: $addToSet and $push also add fields to the array
// The former has the same data, so it is not added. If not, add.
// The latter is added regardless of whether there is the same data in the array.
Delete data within a nested array
db.collection('users').updateOne({username: "222"}, {
	$pull: {
		task: {
			date: new Date().getTime(),
			newTask: [],
			onGoing: [],
			finished: [],
			abandoned: []
		}
	}
})
Modify the value of a field in the data in the array


Now, update the value of newTask to ['Hello ',' world ']

Practice:

db.collection('users').updateOne({username: "222", 'task.newTask': []}, {
	$set: {
		{'task.$.newTask': ['hello', 'world']}
	}
})

/*
There are two points to note:
1:  In the query criteria, the element to be updated must be written.
For example, to update the newtask, you need to write 'task newTask': []
2:  Note the writing in $set -- 'task. $ newTask' . 
The $here is the bitwise character of the array, which can be understood as the element in the array of task
task.$ Represents the first element of the task array
task.$[] Represents all elements in the task array
task.$[index] Represents the element in the task array with index as the subscript
*/

check

raw data:

Find a document

Now, we need to find a document where one is "hello" and two is "world",

Practice:

db.collection('users').findOne({one: 'hello', two: 'world'}).toArray ((err, data) => {
if(err) {
   console.log(err);
}else {
   console.log(data);
 }
})
// The findOne here can also be changed to find
Find multiple documents

Now we're going to find all the documents where one is "hello":

db.collection('users').findMany({one: 'hello'}).toArray ((err, data) => {
if(err) {
   console.log(err);
}else {
   console.log(data);
 }
})
Find all documents in the collection
db.collection('users').find({})
Find by criteria

Let's introduce the operators First:

$lt: // less than
$lte: // Less than or equal to
$gt: // greater than
$gte: // Greater than or equal to
$ne: // Not equal to

Now let's look for documents with number less than 50:

db.collection('users').find({number: [$lt: 50]}).toArray()
  • $or operator

Now, look up the documentation for {one: 'hello'} or {two: 'world'}:

db.collection('users').find({$or:[{one: 'hello'},{two: 'world'}]}).toArray()

Note: the search condition in the update method can also be used as the search condition.

Reference documents

  • Front end learning (water blowing) group: 1064534163
  • Rookie tutorial mongodb: https://www.runoob.com/mongodb/mongodb-update.html
  • Common operators: https://www.cnblogs.com/angongIT/p/11170099.html
  • Addition, deletion, modification and query of embedded array: https://www.cnblogs.com/KnowEditByW/p/9290593.html
  • Multi level document update data: https://www.jb51.net/article/215577.htm
  • $unset operator usage: https://blog.csdn.net/yaomingyang/article/details/78791297
  • mongodb Chinese document: https://docs.mongoing.com/

Package with mongodb

  • Source code available https://gitee.com/guozia007/cuckoo/tree/master/server/db View in this project.
  • The following is the package code:
// Because the most time-consuming operation of the database is to connect to the database, the database is encapsulated to solve the problem of repeatedly connecting to the database
// After simple encapsulation, there is the problem of multiple instantiations calling data connection repeatedly, so it should be solved during encapsulation.
const {MongoClient, ObjectId} = require('mongodb'); // Import database
const config_db = require('./config'); // Import db configuration file

/**
 * Encapsulate db Library
 */

class Db {
  // Create a static method to solve the problem of multiple instances repeatedly connecting to the database
  // For example, the instance testDb1 has been connected to the database,
  // However, the instance testDb2 will still call the connect method to connect to the database, wasting performance
  // What we need is that when the previous instance has connected to the database, 
  // If the database is in the connected state, future instances do not need to be connected
  static getInstance() {
    if(!Db.instance) { // If no instance exists
      Db.instance = new Db(); // Create an instance
    }
    return Db.instance;
  }
  constructor() {
    // Set a property to solve the problem that multiple methods on an instance repeatedly call the database connection
    // For example, if the instance testDb has already connected to the database, do not connect repeatedly when using find query
    this.dbClient = ''; 

    this.connect(); // Connect to the database during initialization
  }

  connect() { // Connect to database
    return new Promise((resolve, reject) => {
      if(!this.dbClient) { // If dbClient does not exist, it means that it has not been called
        MongoClient.connect(config_db.dbUrl, (err, client) => {
          if(err) {
            reject(err);
          } else {
            this.dbClient = client.db(config_db.dbName);
            resolve(this.dbClient);
          }
        })
      } else { // If it already exists, it indicates that it has been called
        return resolve(this.dbClient);
      }
    })
  }

  add(collectionName, jsonData) { // Add data
    return new Promise((resolve, reject) => {
      this.connect()
      .then(db => {
        db.collection(collectionName)
        .insertOne(jsonData, (err, data) => {
          if(err) {
            reject(err);
          } else {
            resolve(data);
          }
        })
      })
      .catch(err => reject(err));
    })
  }

  addMany(collectionName, jsonArr) { // Add multiple pieces of data
    return new Promise((resolve, reject) => {
      this.connect()
      .then(db => {
        db.collection(collectionName)
        .insertMany(jsonArr, (err, data) => {
          if(err) {
            reject(err);
          } else {
            resolve(data);
          }
        })
      })
      .catch(err => reject(err));
    })
  }

  /**delete */
  delOne(collectionName, jsonData) {
    return new Promise((resolve, reject) => {
      this.connect()
        .then(db => {
          db.collection(collectionName)
            .deleteOne(jsonData, (err, data) => {
              if(err) {
                reject(err);
              }else {
                resolve(data);
              }
            })
        })
    })
  }

  delMany(collectionName, jsonData) {
    return new Promise((resolve, reject) => {
      this.connect()
        .then(db => {
          db.collection(collectionName)
            .deleteMany(jsonData, (err, data) => {
              if(err) {
                reject(err);
              }else {
                resolve(data);
              }
            })
        })
    })
  }

  update(collectionName, jsonData1, jsonData2) { // Update a piece of data
    return new Promise((resolve, reject) => {
      this.connect()
      .then(db => {
        db.collection(collectionName)
        .updateOne(jsonData1,
          {
            $set: jsonData2,
          },
            (err, data) => {
          if(err) {
            reject(err);
          } else {
            resolve(data);
          }
        })
      })
    })
  }

  update_delOne(collectionName, jsonData1, jsonData2) { // Delete a piece of data when updating
    return new Promise((resolve, reject) => {
      this.connect()
      .then(db => {
        db.collection(collectionName)
        .updateOne(jsonData1,
          {
            $unset: jsonData2,
          },
            (err, data) => {
          if(err) {
            reject(err);
          } else {
            resolve(data);
          }
        })
      })
    })
  }

  /**
   * Added tasks for the first time in the day
   * You need to add an object to the task array
   * {
        date: new Date().getTime(),
        newTask: [],
        onGoing: [],
        finished: [],
        abandoned: []
      }
   */
  update_new_task(collectionName,jsonData1, jsonData2) {
    return new Promise((resolve, reject) => {
      this.connect()
        .then(db => {
          db.collection(collectionName)
          .updateOne(jsonData1, {
            $addToSet: {task: jsonData2}
          }, (err, data) => {
            if(err) {
              reject(err);
            } else {
              resolve(data);
            }
          })
        })
    })
  }

  update_$_data(collectionName,jsonData1, jsonData2) { // Update the value of a field within a nested array
    return new Promise((resolve, reject) => {
      this.connect()
        .then(db => {
          db.collection(collectionName)
            .updateOne(jsonData1, {
              $set: jsonData2
            }, (err, data) => {
              if(err) {
                reject(err);
              } else {
                resolve(data);
              }
            })
        })
    })
  }


  find(collectionName, jsonData) { // Find data
    return new Promise((resolve, reject) => {
      this.connect()
      .then(db => {
        db.collection(collectionName).find(jsonData)
        .toArray((err, data) => {
          if(err) {
            reject(err);
          } else {
            resolve(data);
          }
        })
      })
      .catch(err => reject(err));
    })
  }

  getObjectId(id) { // Get_ id, because it is used in query_ The value of id is data of type ObjectId()
    return new ObjectId(id);
  }

}

// const testDb = Db.getInstance();

// testDb.add('users', {hello: "world"})
// . Then (data = > console.log ('successfully added ', data));
// testDb.addMany('users', [{one: 'first data'}, {two: 'second data'}]);

// testDb.delOne('users', {one: "first data"});
// testDb.delMany('users', {one: "first data"});

// testDb.update('users', {one: "hello"}, {one: 'dilireba', age: 18})
// . Then (data = > console.log ('update succeeded ', data));
// testDb.update_delOne('users', {two: 'world'}, {two: ''});

// testDb.find('users', {})
// . Then (data = > console.log ('Get data ', data));

// testDb.update_new_task('users', {username: "222"}, 
// {
//   date: new Date().getTime(),
//   newTask: [],
//   onGoing: [],
//   finished: [],
//   abandoned: []
// })
// testDb.update_$_data('users', {username: "222", 'task.newTask': []}, {
//   'task.$.newTask': ['hello', 'world']
// })

module.exports = Db.getInstance();

Keywords: node.js Big Data MongoDB

Added by h.a.visser on Fri, 17 Dec 2021 23:29:09 +0200