Home > Back-end >  MongoDB aggregation for finding an index of array nested object with $gt condition
MongoDB aggregation for finding an index of array nested object with $gt condition

Time:09-22

I am trying to get the positional index of an array element (to push more elements at $position). I'm specifically targeting a single document (say, id=x)

Simplified document:

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

Aggregation pipeline:

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

This works to return matchedIndex=1 . Now I would like to find the index of 'samples' where timestamp is greater than say 235, which should return '2'

I have tried combinations of:

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

I understand this wont work, I'm just not sure how to go about it.

The purpose is to insert many elements between timestamps. Maybe there is a better way entirely to do this. Thanks

CodePudding user response:

Instead of using "$samples.timestamp" as first argument you can use $map there to transform it into an array of true and false values depending on your condition, try:

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

Mongo Playground

  • Related