1

I have this kind of document

{ 
    "_id" : ObjectId("573342930348ce88ff1685f3"),
    "presences" : [
        {
            "_id" : ObjectId("573342930348ce88ff1685f2"), 
            "createdAt" : NumberLong(1458751869000) 
        }, 
        {
            "_id" : ObjectId("573342930348ce88ff1685f5"), 
            "createdAt" : NumberLong(1458751885000)
        }, 
        {
            "_id" : ObjectId("573342930348ce88ff1685f7"), 
            "createdAt" : NumberLong(1458751894000)
        }
    ]
}

How can I extract first and last presences element to new properties firstPresence and lastPresence like this?

{ 
    "_id" : ObjectId("573342930348ce88ff1685f3"),
    "firstPresence": {
        "_id" : ObjectId("573342930348ce88ff1685f2"), 
        "createdAt" : NumberLong(1458751869000) 
    },
    "lastPresence": {
        "_id" : ObjectId("573342930348ce88ff1685f7"), 
        "createdAt" : NumberLong(1458751894000)
    },
    "presences" : [
        ...
    ]
}

I want to use a query that can be applied to all documents in one time.

2 Answers 2

2

You need to $unwind your presences array to do the aggregation. Before grouping you can sort them by createdAt to utilize $first and $last operators.

db.collection.aggregate(
    [
        { $unwind: "$presences" },
        { $sort: { "presences.createdAt": 1 } },
        { 
            $group: {
                _id: "$_id",
                "presences": { $push: "$presences" },
                "lastPresence": { $last: "$presences" },
                "firstPresence": { $first: "$presences" },
            } 
        },
        { $out : "collection" }
    ])

Last aggregation pipeline ($out) will replace existing collection.

Sign up to request clarification or add additional context in comments.

2 Comments

It will replace my documents or create new ones?
Sorry, I thought that you want to project your data. If you need to replace existing collection you should add $out as a last step - just as I edited my answer.
0

According to above mentioned description as a solution to it please try executing following aggregate query into MongoDB shell

   db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $project: {

                first: {
                    $arrayElemAt: ["$presences", 0]
                },
                last: {
                    $arrayElemAt: ["$presences", -1]
                },
                presences: 1
            }
        },

    ]



);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.