Storing dynamic value in mongoDB which refers to other properties

Viewed 60

I am working in Node js - mongoDB . I have a requirement where I need to store and retrieve data in mongoDB which are dynamic and refers to other keys in the collection. Example: firstName : string lastName : string, fullName : string

Assume we insert a record like below

{ firstName : "hello", lastName : "world", fullName : " firstName lastName" }

Now when we retrieve the record the fullName field is expected to show the actual name . In front end , we could use something like string interpolation to achieve this in angular. Is there any way I can directly handle this expression in backend . My actual use case involves more complex structures hence it is not possible to rely on front end.

1 Answers

Mongo aggregations can be used to do this :

let userProps = await users.aggregate([
  {$match: {_id: ObjectId(_id)}},
  {$unset : ["unusedProps"]},
  {$addFields:{fullName: { $concat: [ "$firstName", " - ", "$lastName" ] }}}
])

This will return a document with a fullName field.

Mongo aggregation can be used to make way more complex queries with the amount of operators builded in =)

Related