1

I have a Devices collection in MongoDB with the following structure:

{
  "group": [
    "group1"
  ]
},
{
  "group": [
    "group1",
    "group2"
  ]
},
{
  "group": []
},
{
  "group": [
    "group3",
    "group4"
  ]
}

How can I filter or aggregate the documents so that I only return the last element of each group array including the blank arrays?

Expected result:

["group1", "group2", "", "group4"]

1 Answer 1

1

You can $group and use $arrayElemAt to get the last element. Additionally you need $ifNull to specify the default value (empty string):

db.collection.aggregate([
    {
        $group: {
            _id: null,
            lastElements: { $push: { $ifNull: [ { $arrayElemAt: [ "$group", -1 ] }, "" ] } }
        }
    }
])

Mongo Playground

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

1 Comment

Thank you @mickl! This is exactly what I needed.

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.