How to query MongoDB to test if an item exists?

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

    Im currently using something like this:

    async check(query) {
      const projection = { _id: 1 };
    
      return !!db.collection.findOne(query, projection);
    }
    

    It will return true or false, of course returning only _id: 1 for smallest data transfer.

提交回复
热议问题