N
N
Ninazu2016-06-27 15:57:27
MongoDB
Ninazu, 2016-06-27 15:57:27

How to return an index in an array?

Mongo version is 2.4.9, so includeArrayIndex for unwind won't work
Let's say a test document

{
    "_id" : ObjectId("576d01fa2e350f30628b4575"),
    "params" : [ 
        /* 0 */
        {
            "project_id" : 101
        }, 
        
        /* 1 */
        {
            "project_id" : 201
        }, 
        
        /* 2 */
        {
            "project_id" : 301
        },
        
        /* 3 */
        {
            "project_id" : 201
        }, 
    ]
}

I'm trying to find duplicates by project_id and return the indexes of the elements in the params array
db.params.aggregate([
    {$unwind: 
        "$params"
    },
    {$group: {
        '_id': '$params.project_id',
        'indexes': {
            $addToSet : 'ARRAY_INDEX' //Тут [1, 3] для project_id = 201
        },
        'count':{
            $sum:1,
        }
    }},
    {$match: {
        'count' : {
            $gt : 1,
        }   
    }},
])

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question