本文介绍了MongoDB-按子树查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档结构与以下所示的简化版本相同:

I have a document structure that the same as the simplified version shown below:

{
  some_other_props: { ... },
  systems: {
    sys1: {
      score: 24,
      metric: 52
    },
    another_sys: {
      score: 9,
      metric: 77
    },
    some_other_sys: {
      score: 12,
      metric: 5
    }
  }
}

我想返回所有子文档score : { "$gte" : 15 }为true的所有文档.

I'd like to return all the documents where score : { "$gte" : 15 } is true for any of the sub-documents.

我能想到的唯一方法是获取system中的键列表,并将其连接到某种或"语句混乱中.但似乎我做错了事.

The only way I could think of doing this was to get the list of keys in system and concat that into some kind of or-statement mess. But it seems like I'm doing something wrong.

我可以重新格式化文档结构,以便每个系统都在自己的文档中...但是some_other_props中还有很多其他信息,现在重新格式化会很麻烦.

I could reformat the document structure so that each system is in its own document... but there's a lot of other information in some_other_props and reformatting now would be a pain.

实际上,我正在尝试做一些更复杂的事情.返回同一系统的scoremetric之间的差异非常大的所有文档.但是在我能够做到这一点之前,我想确保我可以如上所述对子树进行简单的查询.

In truth I'm trying to do something a bit more complex. Return all the documents where the difference between the score and metric of the same system are very different. But before I can do that I wanted to make sure I could just do simple queries on sub-trees as I've shown above.

有人可以建议如何在MongoDB中查询子树吗?

Can anyone suggest how to query sub-trees in MongoDB?

推荐答案

您应考虑将子文档存储为数组:

You should consider storing the sub-documents as an array:

{
  some_other_props: { ... },
  systems:
    [ {id: 'sys1',
      score: 24,
      metric: 52
    },
    { id: 'another_sys',
      score: 9,
      metric: 77
    }]

}

然后,您只需查询find 'systems.score' : { '$gte' : 15 },如果您认为需要,也可以为"systems.score"建立索引.

Then you can just query find 'systems.score' : { '$gte' : 15 } , and you can also build an index for 'systems.score' if you feel that you need it.

这篇关于MongoDB-按子树查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:34
查看更多