SiteCozy

  • My account

How to delete several records in MongoDB using NodeJS

2018-09-29

To achieve this we will use MongoDB driver (npm i mongodb), promise and the deleteMany method. The following code will find all the documents with a field this and a value equal to 1. Node that we copy the parameter ok in db1 otherwise, the database object would not be accessible from the subsequent blocks. For example, ok.close() would not work.

const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://192.168.1.203:27017';
options = {
    useNewUrlParser: true
};

MongoClient.connect(url, options).then(function (ok) {
        
       db1 = ok;
       dbName = 'testdb';
        return db1.db(dbName).collection('test').deleteMany({"this":1});

    })
    .then(function (dbs) {
console.log(dbs);
db1.close();
    });

In the mongo shell, after selecting the database (use testdb), there is no records left because it deleted all the documents in which there was “this”:1 We ran the command before and after running the NodeJS code.

MongoDB Enterprise > db.test.find()
{ "_id" : ObjectId("5bab61018df000e560655d2d"), "this" : 1, "another" : "this is a test" }
{ "_id" : ObjectId("5bab6110b8724ae561d7191d"), "this" : 1, "another" : "this is a test" }
MongoDB Enterprise > db.test.find()
MongoDB Enterprise > 

The deleteMany method returns an object which is dbs in our code. The result is the following:

CommandResult {
  result: { n: 2, ok: 1 },
  connection:
   Connection {
     domain: null,
     _events:
      { error: [Object],
        close: [Object],
        timeout: [Object],
        parseError: [Object] },
     _eventsCount: 4,
     _maxListeners: undefined,
     options:
      { host: '192.168.1.203',
        port: 27017,
        size: 5,
        minSize: 0,
        connectionTimeout: 30000,
        socketTimeout: 360000,
        keepAlive: true,
        keepAliveInitialDelay: 300000,
        noDelay: true,
        ssl: false,
        checkServerIdentity: true,
        ca: null,
        crl: null,
        cert: null,
        key: null,
        passPhrase: null,
        rejectUnauthorized: false,
        promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false,
        reconnect: true,
        reconnectInterval: 1000,
        reconnectTries: 30,
        domainsEnabled: false,
        disconnectHandler: [Object],
        cursorFactory: [Object],
        emitError: true,
        monitorCommands: false,
        promiseLibrary: [Function: Promise],
        clientInfo: [Object],
        servers: [Array],
        useNewUrlParser: true,
        db: 'admin',
        dbName: 'admin',
        socketTimeoutMS: 360000,
        connectTimeoutMS: 30000,
        bson: BSON {} },
     id: 0,
     logger: Logger { className: 'Connection' },
     bson: BSON {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: '192.168.1.203',
     family: undefined,
     keepAlive: true,
     keepAliveInitialDelay: 300000,
     noDelay: true,
     connectionTimeout: 30000,
     socketTimeout: 360000,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     crl: null,
     cert: null,
     key: null,
     passphrase: null,
     ciphers: null,
     ecdhCurve: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions:
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     flushing: false,
     queue: [],
     connection:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: null,
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        _bytesDispatched: 434,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        _idleTimeout: 360000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 303,
        _destroyed: false,
        [Symbol(asyncId)]: 5,
        [Symbol(bytesRead)]: 0,
        [Symbol(asyncId)]: 8,
        [Symbol(triggerAsyncId)]: 1 },
     writeStream: null,
     hashedName: 'ecc4c59c3c6dde71259f7aabc040337c19f4b64c',
     workItems: [],
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null },
  message:
   Response {
     parsed: true,
     raw: <Buffer 3c 00 00 00 6d 64 00 00 02 00 00 00 01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 18 00 00 00 10 6e 00 02 00 00 00 01 6f 6b ... >,
     data: <Buffer 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 18 00 00 00 10 6e 00 02 00 00 00 01 6f 6b 00 00 00 00 00 00 00 f0 3f 00>,
     bson: BSON {},
     opts:
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     length: 60,
     requestId: 25709,
     responseTo: 2,
     opCode: 1,
     fromCompressed: undefined,
     responseFlags: 8,
     cursorId: Long { _bsontype: 'Long', low_: 0, high_: 0 },
     startingFrom: 0,
     numberReturned: 1,
     documents: [ [Object] ],
     cursorNotFound: false,
     queryFailure: false,
     shardConfigStale: false,
     awaitCapable: true,
     promoteLongs: true,
     promoteValues: true,
     promoteBuffers: false,
     index: 44,
     hashedName: 'ecc4c59c3c6dde71259f7aabc040337c19f4b64c' },
  deletedCount: 2 }

Related Posts:

  • How to update several doc. in MongoDB with NodeJS
  • How to update one doc. in MongoDB with NodeJS
  • How to delete one doc. in MongoDB with NodeJS
Download our Broken link checker freeware here Buy a license key for the Sitecozy broken link checker

Customer Login

Lost password?

Categories

  • Webmaster advice
  • SEO advice
  • Web hosting
  • SiteCozy link checker KB
  • WordPress theme & plugin reviews
  • All articles
Disclosure: We are a professional review site that receives compensation from the companies whose products we review. We test each product thoroughly and give high marks to only the very best. We are independently owned and the opinions expressed here are our own.

Copyright Sitecozy 2018