Database
[]
Query
db.collection.aggregate([{"$match":{"_id":123}},{"$unionWith":{"coll":"collection","pipeline":[{$documents:[/** put the "template" you want to insert here*/{"_id":123,"login":"john","details":{"a":"abc","verified":true},"locations":[],"profiles":[],"posts":[]}]}]}},{$group:{_id:"$_id",/** if the user exists, it will be the first document picked*/doc:{$first:"$$ROOT"}}},{"$replaceRoot":{"newRoot":"$doc"}},{"$set":{"locations":{"$let":{"vars":{/** your location input here*/"locationInput":{"country":"TEST","region":"test","city":"test"}},"in":{"$cond":{"if":{$ne:["$$locationInput",/** last location*/{$last:"$locations.location"}]},"then":{"$concatArrays":["$locations",["$$locationInput"]]},"else":"$locations"}}}}}},{"$set":{"profiles":{"$let":{"vars":{"profileInput":{/** your profile hash input here*/"preference":{"a":"test","b":"test"},"details":{"a":"test","b":"test"},"hash":"hash456","createdAt":"$$NOW"}},"in":{"$cond":{"if":{$ne:["$$profileInput.hash",/** last profile*/{$last:"$profiles.hash"}]},"then":{"$concatArrays":["$profiles",[/** your profile to be inserted here*/"$$profileInput"]]},"else":"$profiles"}}}}}},{"$set":{"posts":{"$let":{"vars":{"postInput":/** your post to be inserted here*/{"postId":456,"message":"test","createdAt":"$$NOW"}},"in":{"$cond":{"if":{$in:["$$postInput.postId","$posts.postId"]},"then":"$posts","else":{"$concatArrays":["$posts",["$$postInput"]]}}}}}}},{"$merge":{"into":"collection","on":"_id"}}])