How to query MongoDB to test if an item exists?

后端 未结 9 1543
囚心锁ツ
囚心锁ツ 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:14

    Starting Mongo 2.6, count has a limit optional parameter, which makes it a viable alternative to find whether a document exists or not:

    db.collection.count({}, { limit: 1 })
    // returns 1 if exists and 0 otherwise
    

    or with a filtering query:

    db.collection.count({/* criteria */}, { limit: 1 })
    

    Limiting the number of matching occurrences makes the collection scan stop whenever a match is found instead of going through the whole collection.


    Starting Mongo 4.0.3, since count() is considered deprecated we can use countDocuments instead:

    db.collection.countDocuments({}, { limit: 1 })
    

    or with a filtering query:

    db.collection.countDocuments({/* criteria */}, { limit: 1 })
    

提交回复
热议问题