gpt4 book ai didi

arrays - 检查 mongo 集合中是否存在值

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:03 37 4
gpt4 key购买 nike

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

var keys = ['key1','key2','key3']//有了这个,我可以轻松地使用 indexOf 函数检查此数组中是否存在某个值,

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

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

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

有谁能告诉我如何插入这个以及如何过滤这些键以检查它们是否已进入集合?

最佳答案

首先,如果您像数组一样存储文档,为什么不将它们存储为数组呢?如果您有关系数据库背景,我可以想象您会想以这种方式存储它,但在 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

编辑:

通过更新,如果 key 不存在,它会将其添加到数组中,但如果您只想知道它是否存在,我认为最好的方法是使用 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 字段。

关于arrays - 检查 mongo 集合中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21366814/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com