【问题标题】:How do I use spring mongo data to query based on the position of an element in an array如何使用spring mongo数据根据数组中元素的位置进行查询
【发布时间】:2017-08-24 16:43:04
【问题描述】:

我有一个 mongo 集合“测试”,其中包含这样的元素(节点数组是一个集合且有意义的顺序):

        "test" : {
        "superiorID" : 1, 
        "nodes" : [
            {
                "subID" : 2
            }, 
            {
                "subID" : 1
            }, 
            {
                "subID" : 3
            }
         ]
        }

        "test" : {
        "superiorID" : 4, 
        "nodes" : [
            {
                "subID" : 2
            }, 
            {
                "subID" : 1
            }, 
            {
                "subID" : 3
            }
         ]
        }

我正在使用 spring Criteria 来尝试构建一个 mongo 查询,它将向我返回“subID”等于用户输入 ID“inputID”的所有元素>' AND 'superiorID' 位置不在 'inputID' 之前(如果上级 id 甚至在 sub ids 不是必需的)。

例如,如果我的用户输入是 3,我不想提取第一个文档,但我想提取第二个文档(第一个存在于节点中的上级在 userInput 节点之前的节点中,第二个的上级 ID 不是等于用户输入)。

我知道 $indexOfArray 函数存在,但我不知道如何将其转换为 Criteria。

【问题讨论】:

  • 可能是我没有正确理解这一点。像db.collection_name.find({"nodes.subID":3, "superiorID":{"$gt":3}}) 这样的东西应该适合你。您可以将代码添加到您尝试过的帖子中吗?

标签: mongodb mongodb-query spring-data-mongodb


【解决方案1】:

你可以通过聚合框架得到你想要的结果。我已经为你做了一个 speude 查询,以显示你应该寻找什么。这返回 doc1 的 showMe = false 和 doc2 的 showMe = true,你可以很自然地匹配。此查询不需要 2 个项目阶段,我这样做只是为了进行一个工作查询,该查询也易于阅读。这将不是一个非常快速的查询。如果您想要快速查询,您可能需要重新考虑您的数据结构。

db.getCollection('test').aggregate([
{ "$project": 
    {
      "superiorIndex":  {"$indexOfArray" : [ "$nodes.subID","$superiorID" ]},
      "inputIndex":  {"$indexOfArray" : [ "$nodes.subID",3 ]},
    }
},
{ "$project": 
    {
      "showMe" : 
      { 
            $cond: 
            { 
                if: { $eq: [ "$superiorIndex", -1 ] }, 
                then: true, 
                else: {$gt:[ "$superiorIndex","$inputIndex"]}
            } 
      }
    }
}
])

【讨论】:

    【解决方案2】:

    db.collection.find({nodes.2.subID:2}) 该查询将从节点字段中查找第二个元素 subid。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      相关资源
      最近更新 更多