繁体   English   中英

MongoDB 聚合用于查找具有 $gt 条件的嵌套 object 数组的索引

[英]MongoDB aggregation for finding an index of array nested object with $gt condition

我正在尝试获取数组元素的位置索引(在$position推送更多元素)。 我专门针对单个文档(例如id=x

简化文件:

{
id:"x",
samples:[{"timestamp":123},{"timestamp":234},{"timestamp":345}}
}

聚合管道:

collection.aggregate([{"$match": {"id": "x"}},
                      {"$project": {"matchedIndex": {"$indexOfArray": ["$samples.timestamp", 234]}}}])

这可以返回matchedIndex=1 现在我想找到时间戳大于235'samples'的索引,它应该返回'2'

我尝试过以下组合:

collection.aggregate([{"$match": {"UUID": "5fd41e35-5e49-O977-t091-6f228bc65e37"}},
                      {"$project": {"matchedIndex": 
                                     {"$indexOfArray": ["$samples.timestamp", 
                                       {"$gt": ["$$timestamp", 235]}]}}}])

我知道这行不通,我只是不确定如何 go 关于它。

目的是在时间戳之间插入许多元素。 也许有更好的方法可以完全做到这一点。 谢谢

除了使用"$samples.timestamp"作为第一个参数,您可以使用$map根据您的条件将其转换为truefalse ,尝试:

{
    "$project": {
        "matchedIndex": {
            "$indexOfArray": [
                { $map: { input: "$samples.timestamp", in: { $gte: [ "$$this", 235 ] } } },
                true
            ]
        }
    }
}

蒙戈游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM