改进 MongoDB 中存在的查询字段 [英] Improve querying fields exist in MongoDB

查看:26
本文介绍了改进 MongoDB 中存在的查询字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我们的客户估算 MongoDB.根据需求,我们需要关联一些实体 ent 名称-值对变量集.

I'm in progress with estimation of MongoDB for our customers. Per requirements we need associate with some entity ent variable set of name-value pairs.

db.ent.insert({'a':5775, 'b':'b1'})
db.ent.insert({'c':'its a c', 'b':'b2'})
db.ent.insert({'a':7557, 'c':'its a c'})

在此之后,我需要集中查询 ent 是否存在字段:

After this I need intensively query ent for presence of fields:

db.ent.find({'a':{$exists:true}})
db.ent.find({'c':{$exists:false}})

每个 MongoDB 文档:

Per MongoDB docs:

$exists 即使使用索引也不是很有效,尤其是.使用 {$exists:true} 因为它将有效地扫描所有索引值.

$exists is not very efficient even with an index, and esp. with {$exists:true} since it will effectively have to scan all indexed values.

那里的专家能否提供更有效的方法(即使改变范式)来快速处理不同的名称-值对

Can experts there provide more efficient way (even with shift the paradigm) to deal fast with vary name-value pairs

推荐答案

你可以像这样重新设计你的架构:

You can redesign your schema like this:

{
  pairs:[
  {k: "a", v: 5775},
  {k: "b", v: "b1"},
  ]
}

然后你索引你的键:

db.people.ensureIndex({"pairs.k" : 1})

在此之后,您将能够按完全匹配进行搜索:

After this you will able to search by exact match:

db.ent.find({'pairs.k':"a"})

如果您使用稀疏索引和@WesFreeman 提出的当前模式,您将需要为要搜索的每个键创建一个索引.如果您的密钥不是静态的,它可能会影响写入性能或者是不可接受的.

In case you go with Sparse index and your current schema, proposed by @WesFreeman, you will need to create an index on each key you want to search. It can affect write performance or will be not acceptable if your keys are not static.

这篇关于改进 MongoDB 中存在的查询字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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