如何查询 MongoDB 以测试项目是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8389811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:21:17  来源:igfitidea点击:

How to query MongoDB to test if an item exists?

mongodbfind

提问by user646584

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.

MongoDB 是否提供查找或查询方法来基于任何字段值测试项目是否存在?我们只想检查是否存在,而不是返回项目的全部内容。

采纳答案by RameshVel

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)

我不相信有直接的方法可以通过它的价值来检查项目的存在。但是你可以通过只检索 id (带字段选择)来做到这一点

db.your_collection.find({..criteria..}, {"_id" : 1});

回答by mnemosyn

Since you don't need the count, you should make sure the query will return after it found the first match. Since count performance is not ideal, that is rather important. The following query should accomplish that:

由于您不需要计数,您应该确保查询在找到第一个匹配项后会返回。由于计数性能并不理想,这相当重要。以下查询应该完成:

db.Collection.find({ /* criteria */}).limit(1).size();

Note that find().count()by default does nothonor the limitclause and might hence return unexpected results (and will try to find all matches). size()or count(true)will honor the limit flag.

请注意,find().count()在默认情况下并没有履行limit条款,并可能因此返回意外的结果(和将尽力找到所有的结果)。size()count(true)将遵守限制标志。

If you want to go to extremes, you should make sure that your query uses covered indexes. Covered indexes only access the index, but they require that the field you query on is indexed. In general, that should do it because a count()obviously does not return any fields. Still, covered indexes sometimes need rather verbose cursors:

如果你想走极端,你应该确保你的查询使用覆盖索引。覆盖索引仅访问索引,但它们要求您查询的字段已编入索引。一般来说,应该这样做,因为 acount()显然不返回任何字段。尽管如此,涵盖的索引有时需要相当冗长的游标:

db.values.find({"value" : 3553}, {"_id": 0, "value" : 1}).limit(1).explain();

{
  // ...
  "cursor" : "BtreeCursor value_1",
  "indexOnly" : true,  // covered!
}

Unfortunately, count()does not offer explain(), so whether it's worth it or not is hard to say. As usual, measurement is a better companion than theory, but theory can at least save you from the bigger problems.

不幸的是,count()不提供explain(),所以值不值得很难说。像往常一样,测量是比理论更好的伴侣,但理论至少可以使您免于面临更大的问题。

回答by Xavier Guihot

Starting Mongo 2.6, counthas a limitoptional parameter, which makes it a viable alternative to find whether a document exists or not:

开始Mongo 2.6,count有一个limit可选参数,这使它成为查找文档是否存在的可行替代方法:

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 deprecatedwe can use countDocumentsinstead:

开始Mongo 4.0.3,因为count()认为已弃用,我们可以countDocuments改用:

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

or with a filtering query:

或使用过滤查询:

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

回答by gihanchanuka

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.

使用 find() + limit() 明显更快,因为 findOne() 将始终读取并返回文档(如果存在)。find() 只返回一个游标(或不返回),并且只有在遍历游标时才读取数据。

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

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

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

(而不是db.collection.findOne({_id: "myId"}, {_id: 1}))。

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

查看更多细节:检查文档是否存在——MongoDB 慢 findOne vs find

回答by ufookoro

I have simply used lodash framework - _isEmpty();

我只是使用了 lodash 框架 - _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();
});

回答by Volodymyr Bobyr

An update to Xavier's answer:

泽维尔答案的更新:

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

Expects a callback as a second argument now, so this can be used instead:

现在期望回调作为第二个参数,因此可以使用它:

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

回答by George Galantsev

If you use Java and Spring you can use that:

如果您使用 Java 和 Spring,您可以使用它:

public interface UserRepository extends MongoRepository<User, ObjectId> {

    boolean existsByUsername(String username);

}

It works for me.

这个对我有用。