How to query MongoDB to test if an item exists?

后端 未结 9 1490
囚心锁ツ
囚心锁ツ 2020-11-27 04:06

Does MongoDB offer a find or query method to test if an item exists based on any field value? We just want check existence, not return the full contents of the item.

相关标签:
9条回答
  • 2020-11-27 04:25

    I have simply used lodash framework - _isEmpty();

    const {
        MongoClient,
        ObjectId
    } = require('mongodb');
    const _ = require('lodash');
    
    MongoClient.connect(testURL, {
        useNewUrlParser: true
    }, (err, client) => {
        let db = client.db('mycompany');
    
        if (err) {
            console.log('unable to connect to the mycompany database');
        } else {
            console.log('test connection to the database');
        };
    
        db.collection('employee').find({
            name: 'Test User'
        }).toArray((err, result) => {
    
            if (err) {
                console.log('The search errored');
            } else if (_.isEmpty(result)) {
                console.log('record not found')
            } else {
                console.log(result);
            };
        });
        client.close();
    });
    
    0 讨论(0)
  • 2020-11-27 04:27

    It is significantly faster to use find() + limit() because findOne() will always read + return the document if it exists. find() just returns a cursor (or not) and only reads the data if you iterate through the cursor.

    db.collection.find({_id: "myId"}, {_id: 1}).limit(1)

    (instead of db.collection.findOne({_id: "myId"}, {_id: 1})).

    Look at more details: Checking if a document exists – MongoDB slow findOne vs find

    0 讨论(0)
  • 2020-11-27 04:32

    I dont believe that there is a straight way of checking the existence of the item by its value. But you could do that by just retrieving only id (with field selection)

    db.your_collection.find({..criteria..}, {"_id" : 1});
    
    0 讨论(0)
提交回复
热议问题