0

I am looking for the most efficient and easy way to merge two BSON Documents. In case of collisions I have already handlers, for example if both documents include Integer, I will sum that, if a string also, if array then will add elements of the other one, etc.

However due to BSONDocument immutable nature it is almost impossible to do something with it. What would be the easiest and fastest way to do merging?

I need to merge the following for example:

{
  "2013": {
   "09": {
    value: 23
   }
  }
}

{
  "2013": {
   "09": {
    value: 13
   },
   "08": {
    value: 1
   }
  }
}

And the final document would be:

{
  "2013": {
   "09": {
    value: 36
   },
   "08": {
    value: 1
   }
  }
}

There is a method in BSONDocument.add, however it doesn't check uniqueness, it means I would have at the end 2 BSON documents with "2013" as a root key, etc.

Thank you!

Alex K
  • 854
  • 9
  • 16

1 Answers1

0

If I understand you inquiry, you are looking to aggregate field data via composite id. MongoDB has a fairly slick aggregate framework. Part of that framework is the $group pipeline aggregate keyword. This will allow you to specify and _id to group by which could be defined as a field or a document as in your example, as well as perform aggregation using accumulators such as $sum.

Here is a link to the manual for the operators you will probably need to use. http://docs.mongodb.org/manual/reference/operator/aggregation/group/

Also, please remove the "merge" tag from your original inquiry to reduce confusion. Many MongoDB drivers include a Merge function as part of the BsonDocument representation as a way to consolidate two BsonDocuments into a single BsonDocument linearly or via element overwrites and it has no relation to aggregation.

Hope this helps.

ndh