N
N
nickerlan2019-07-10 11:41:01
MongoDB
nickerlan, 2019-07-10 11:41:01

How to merge Mongo arrays by unique key?

Given:
1. Array addTags = [ 'tag1', 'tag2', ... ]
2. Simple selection like condition = {param:"value"}
3. Object like this:

someObject {
  ...
  param: String,
  tags:[{
        name:String,
        timestamp:Date
    }]
}

Task:
Add the missing tags from the addTags array to all objects matching the condition selection based on the match between the name field and the addTags element. Assign the newly added tags a timestamp corresponding to the current time.
Question:
Is this solved by means of Mongo?
The solution "on the forehead" on JS seems to me painfully suboptimal, it is seen in the following spirit:
const tagDates = addTags.map(tag=>{name:tag, timestamp:Date.now()}
findMany(condition).then(
  foundObjects=>foundObjects.forEach(object=>{
    const newTags = mergeByName(object.tags, tagDates)
    updateOne({id:object.id},{tags:newTags}).then()
  })
)

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