0

I have a collection like this:

collection base:

{
    _id:"a"
    field:[
        {
          _id:"aa",
          field1:"aa1"
        },
        {
          _id:"ab",
          field2:"ab2"
        },
    ]
}

what query can I use to have a result like this:

{
    _id:"a"
    field:            
        {
          _id:"ab",
          field2:"ab2",
          field1:"aa1"
        },        
}

In other words i want use this function as mongoose query on field array:

field.reduce((p,c)=>({...p,...c}),{})
2
  • on what base you want to select _id:"ab" why its not _id:"aa"? Commented Apr 11, 2021 at 5:53
  • i want to merge array items from start to end into one object Commented Apr 11, 2021 at 5:55

1 Answer 1

1
  • $reduce to iterate loop of field, set initialValue to empty object,
  • $mergeObjects to merge initialValue means $$value and $$this means current object
db.collection.aggregate([
  {
    $addFields: {
      field: {
        $reduce: {
          input: "$field",
          initialValue: {},
          in: { $mergeObjects: ["$$value", "$$this"] }
        }
      }
    }
  }
])

Playground

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

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.