Is there a way to insert a document in collection using aggregation pipeline?

Hi there, are there any ways to insert a document using aggregation pipeline?

I am not sure of your use-case but you could take a look at

Hi @steevej , I am pretty much looking for a aggregation pipeline substitution of db.collection().insert() function

That is what $merge is about. It insert documents, created by the execution of an aggregation, into a target collection.

An alternative is $out.

I am pretty much looking for a aggregation pipeline substitution of db.collection().insert()

Why can’t you just use insert? Can you elaborate on the functionality you need? Rather than $merge I suspect you probably want to use update with upsert flag set to true and aggregation pipeline syntax to specify the update (available since version 4.2).

Asya

Yes, there is. It’s not a legitimate way, but it’s a workaround.
I wanted to do a complex upsert, which was not supported by a simple update. I stumbled upon this thread, but I didn’t give up. After some tweaking I was able to do it.

Even if you have 0 documents, you can make one using any stage to obtain at least one property. From then on, it’s game on.
This is just an example to upsert 1 document at time, the trick can be achieved using $facet. Below an example:
[ { '$facet': { dummy: [ { '$project': { validPropertyOfCollection: '' } } ] } }, { '$set': { yourProperties: 'test' } }, { '$unset': 'dummy' }, ... complexPipeline { '$merge': { into: 'yourCollection', on: 'yourUniqueField', whenMatched: 'replace', whenNotMatched: 'insert' } } ]

1 Like

The $documents stage might also be used when you do not have any collection to start with.

1 Like