在mongodb中使用随机键通过嵌套文档值查找 [英] Find by nested document values with random keys in mongodb

查看:42
本文介绍了在mongodb中使用随机键通过嵌套文档值查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有以下集合结构:


I have the following collection structure:

{
   _id : ObjectId('...'),
   randomKeysSubdocument : {
       'jhaksdf' : 'something',
       'jio348akgqug' : 'something else',
       'kgowe98akjg' : 'more things',
   }
}

其中 randomKeysSubdocument 是具有以编程方式生成的随机密钥的子文档(我不知道它们的名称).
有没有一种方法可以查询 randomKeysSubdocument 值,就像如果 randomKeysSubdocument 是数组一样查询它们:

where randomKeysSubdocument is a subdocument with random keys generated programmatically (and i don't know their names).
Is there a way how I can query by randomKeysSubdocument values in the same way as I would query them if randomKeysSubdocument were an array:

{
   _id : ObjectId('...'),
   randomKeysSubdocument : [
       'something',
       'something else',
       'more things',
   ]
}

查询:

db.my_collection.find({
    randomKeysSubdocument : 'something'
})

推荐答案

所以应该清楚你不应该这样做.用不同的键名构造文档不是一个好的模式,当然也不适用于 MongoDB 或一般数据库搜索.

So it should be clear that you should not do this. Structuring documents with different key names is not a good pattern, and certainly does not work well with MongoDB or general database searching.

只能索引数据",因此对您来说更好的结构是:

Only "data" can be indexed, so a better structure for you would be:

{
   randomKeysSubdocument : [
       { "key": 'jhaksdf', "data": 'something' },
       { "key": 'jio348akgqug', "data": 'something else' }
       { "key": 'kgowe98akjg', "data": 'more things' }
   ]
}

您注意到的在数组中搜索已经很容易了:

Where searching in the array as you note is already easy:

db.collection.find({ "randomKeysSubdocument.data": "something" })

当然,这可以使用索引来加快速度.

And of course that can use an index to make things faster.

您目前拥有的东西的方式必须依赖于 $where 用于匹配并且不能为此使用索引:

The way you currently have things you have to rely on JavaScript processing of $where for the match and cannot use an index for this:

db.collection.find(function() {
    var doc = this.randomKeysSubDocument;
    return Object.keys(doc).some(function(key) {
       return doc[key] == "something";
    });
})

这将比标准查询慢得多,并且必须测试集合中的每个文档.

Which is going to be much slower than a standard query and must test every document in the collection.

对我来说,我会改变结构并摆脱使用数据"作为键名的模式,而是将它放在数据中而不是它所属的地方,并保持结构一致以进行搜索.

For mine, I would change the structure and move away from the pattern of using "data" as the names of keys, but put it in data instead where it belongs and keeps structures consistent for searching.

这篇关于在mongodb中使用随机键通过嵌套文档值查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆