【问题标题】:Check if value exist in mongo collection检查 mongo 集合中是否存在值
【发布时间】:2014-02-17 11:05:59
【问题描述】:

我在 node js 中工作,我正在使用 mongo (我绝对是初学者)。现在我需要有一个基本上需要看起来像这个数组的集合

var keys = ['key1','key2','key3'] // 有了这个我可以很容易地用 indexOf 函数检查这个数组中是否存在一些值,

现在我需要在 mongo 中进行集合,只需要存储用户创建的密钥,如果密钥已经存在于集合中,则无需执行任何操作。

//我的键看起来像这样,可以是一个字符串也可以是一个字符串数组

Keys = 'home4.car3' or Keys = ['home4.car3','home2.car4']

// 我是这样插入的

db.collection('keys',function(err, collection){
            collection.insert(Keys, {safe:true}, function(err, result) {
                if (err) {
                    res.send({'error':'An error has occurred'});
                } else {
                    console.log("success");
                }
            });
        });

现在这是我第一次将两个键的数组插入 db ,然后在那个字符串之后发生的情况:

https://gist.github.com/anonymous/fc7730e398519cffde3f

有谁可以告诉我如何为此插入以及如何过滤这些键以检查它们是否在集合中?

【问题讨论】:

    标签: arrays node.js mongodb


    【解决方案1】:

    首先,如果您将文档存储为数组,为什么不将它们存储为数组?如果您来自关系数据库背景,我可以看到您会很想以这种方式存储它,但在 Mongo 中,如果它像一个数组,则应该将它存储为一个数组。

    {
        "_id" : ObjectId("52e5361f30f28b6b602e4c7f"),
        "0" : "h",
        "1" : "o",
        "2" : "m"
    }
    

    应该是:

    {
        "_id" : ObjectId("52e5361f30f28b6b602e4c7f"),
        "keys" : [ "h", "o", "m" ]
    }
    

    在这种情况下,Mongo 有一个名为 $addToSet 的便捷运算符,它的工作原理与 $push 一样,只是它只会在不存在时将其添加到数组中。操作看起来像这样:

    collection.update( query, { $addToSet : { 'keys' : 'l' }}, callback );
    // add key 'l'
    
    collection.update( query, { $addToSet : { 'keys' : 'm' }}, callback );
    // looks in document, sees 'm' in array, and does nothing
    

    编辑:

    随着更新,如果它不存在,它会将密钥添加到数组中,但如果您只想知道它是否存在,我认为最好的方法是使用findOne

    // find the doc by _id  and the value you want in keys, returns null if it's not a match
    collection.findOne({ _id : 52e5361f30f28b6b602e4c7f, 'keys' : 'l' }, function(err, doc) {
        if( doc == null ) {
            // do whatever you need to do if it's not there
        } else {
            // do whatever you need to if it is there
        }
        db.close();
    }
    

    要保持插入不变,您只需将 Keys 更改为:

    Keys = { 'keys' : [ 'key1', 'key2', 'key3' ] };
    

    并且插入不需要更改。此外,在您的集合中,您可能希望将 _id 更改为 username 或在文档中添加 username 字段。

    【讨论】:

    • 如果事件不在数组中,如何获取事件,因为我需要触发该事件的函数?你能告诉我插入现在的样子吗
    • 没问题!如果您的问题已成功回答,请接受答案。
    猜你喜欢
    • 2012-11-03
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2012-11-06
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多