Mongodb $merge not working as it should

I am merging one collection documents into another collection using mongodb merge aggregation. I am trying to merge 10 fields of basic details i.e. name, age, dob etc. into another collection using a unique key. My mongodb query is given below :

db.collection1.aggregate([
    {
    $project:
        {
        _id:0, 
        <fieldsList>:1
        }
    },
    {
        $merge : { into: "collection2", on: "<unique_field>",  whenMatched: "keepExisting", whenNotMatched: "insert" 
     }
    }
])

The query gives me an error given below :

The full response is:

{ 
    "operationTime" : Timestamp(1677514685, 51), 
    "ok" : 0.0, 
    "errmsg" : "BSONObj size: 20141031 (0x13353E7) is invalid. Size must be between 0 and 16793600(16MB) First element: update: \"collection2\"", 
    "code" : NumberInt(10334), 
    "codeName" : "BSONObjectTooLarge", 
    "$clusterTime" : {
        "clusterTime" : Timestamp(1677514685, 51), 
        "signature" : {
            "hash" : BinData(0, "7xcBrDcNZ+/bCEJ2gSFuIojEkjI="), 
            "keyId" : NumberLong(7174701554677579780)
        }
    }
}

Total documents to be merged around 6 million.

This makes me wonder that why am i getting document size error when no single document that will be merged is more than even 512 kb. Let me know if i am understanding the merge query wrong.

I expect that the query should work fine because no single document is more than 16 MB.

Hi @jony_chawla and welcome to the MongoDB community forum!!

Does this happen using readPreference secondary (and not reproducible with readPreference primary)? If yes, I believe you may have experienced SERVER-66289 which was resolved in MongoDB 4.4.18, 5.0.14, and 6.0.3.
If you’re not using the latest version 4.4.19, 5.0.15 and 6.0.4, could you please upgrade to the latest version and let us know if the issue still persists?

Best Regards
Aasawari

Hi @Aasawari,
The issue was already resolved on the same day, following the upgrade process from 4.4.17 to 4.4.19.

Thanks and Regards,
Jony

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.