$out Stage - Honor existing indexes

The $out stage will overwrite the collection if a collection already exists. And it will honor all the indexes of the previous collection.

My question is if we have an index on a field in a collection and this particular files is not part of the collection created (overwritten) as a part of the $out stage. Will the index be maintained or will be be removed/deleted from the DB.

Hi @Mahesh_Sammatashetti,

I think this answers your question: https://docs.mongodb.com/manual/reference/operator/aggregation/out/#replace-existing-collection

If the output collection already exists, MongoDB creates a new temp collection, recreates the same indexes from the “old” collection, imports all the documents in this temp collection and finally replaces the “old” collection in a single atomic operation by the new one.

If this isn’t the expected behaviour you are looking for, have a look to $merge.

Here is a comparison between $out and $merge: https://docs.mongodb.com/manual/reference/operator/aggregation/out/#comparison-with--merge

$merge is new from 4.2 so more recent and more flexible.


Hi @Mahesh_Sammatashetti

Maxime gave a great answer. And, if I may add to that: Indexes in output collection are untouched regardless of the existence of a field. Here’s a snippet in action.

db.foo.insertMany([{ name: "first", score: 80   }, { name: "second", score: 76}, { name: "third", score: 70}])
db.foo.createIndex({ score: 1 })

db.bar.insertMany([{ name: "first", score: 80   }, { name: "fourth", score: 60}])
db.bar.createIndex({ name: 1 })


    { $project: { score:1 }},
    { $out: "bar"}


//indexes in replaced-output collection are untouched 


1 Like