【问题标题】:MongoDB: Is a range query possible using multikeys?MongoDB:是否可以使用多键进行范围查询?
【发布时间】:2011-03-04 00:06:48
【问题描述】:
var jd = {
  type: "Person",
  attributes: {
    name: "John Doe",
    age: 30
  }
};

var pd = {
  type: "Person",
  attributes: {
    name: "Penelope Doe",
    age: 26
  }
};

var ss = {
  type: "Book",
  attributes: {
    name: "The Sword Of Shannara",
    author: "Terry Brooks"
  }
};

db.things.save(jd);
db.things.save(pd);
db.things.save(ss);
db.things.ensureIndex({attributes: 1})
db.things.find({"attributes.age": 30}) // => John Doe
db.things.find({"attributes.age": 30}).explain() // => BasicCursor... (don't want a scan)
db.things.find({"attributes.age": {$gte: 18}) // John Doe, Penelope Doe (via a scan)

目标是通过范围查询对所有属性进行索引和搜索,并且实际使用索引(而不是集合扫描)。不知道文档将具有哪些属性。我已经阅读了关于多键的信息,但它们似乎只能(按索引)与完全匹配的查询一起使用。

Multikeys 更喜欢这种格式的文档:

var pd = {
  type: "Person",
  attributes: [
    {name: "Penelope Doe"},
    {age: 26}
  ]
};

有没有一种模式可以通过一个索引使用范围按属性查找项目?

编辑:

在无模式数据库中,可能具有无限的类型数组是有意义的,但集合名称实际上暗示了某种类型。但是,如果我们走极端,我们希望在一个集合中允许任意数量的类型(这样我们就不必为用户可能想象的每个可能的自定义类型定义一个集合)。因此,通过仅具有单个深度索引(支持范围查询)的(任何类型的)属性进行搜索使得这种事情变得更加可行。在我看来,无模式数据库很自然。

如果您想投票,请打开一张票:

http://jira.mongodb.org/browse/SERVER-2675

【问题讨论】:

  • 我会在groups.google.com/group/mongodb-user 中发布这个问题,并从开发人员自己那里得到答案 - 他们非常响应。
  • 感谢您的提示。我就是这么做的。 :)

标签: mongodb indexing


【解决方案1】:

是的,范围查询适用于多键。然而,多键用于数组而不是嵌入对象。

在上面的例子中尝试

db.things.ensureIndex({"attributes.age": 1})

【讨论】:

  • 我们的目标是避免索引“年龄”或任何一个属性,但要索引所有“属性”。关键是我可以拥有任何属性键(例如“dob”、“name”、“hai​​r_color”),并且我应该对它们进行索引访问。
【解决方案2】:

可以使用多键进行范围查询;但是,表达查询可能很棘手。

【讨论】:

    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 2018-09-29
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多