Can MongoDB and its drivers preserve the ordering of document elements

前端 未结 4 1099
一生所求
一生所求 2020-12-06 06:06

I am considering using MongoDB to store documents that include a list of key/value pairs. The safe but ugly and bloated way to store this is as

[ [\'k1\' :          


        
4条回答
  •  再見小時候
    2020-12-06 06:17

    Though it's true that, as of Mongo 2.6.1, it does preserve order, one should still be careful with update operations.

    mattwad makes the point that updates can reorder things, but there's at least one other concern I can think of.

    For example $addToSet:

    https://docs.mongodb.com/manual/reference/operator/update/addToSet/

    $addToSet when used on embedded documents in an array is discussed / exemplified here: https://stackoverflow.com/a/21578556/3643190

    In the post, mnemosyn explains how $addToSet disregards the order when matching elements in its deep value by value comparison.

    ($addToSet only adds records when they're unique)

    This is relevant if one decided to structure data like this:

    [{key1: v1, key2: v2}, {key1: v3, key2: v4}]
    

    With an update like this (notice the different order on the embedded doc):

    db.collection.update({_id: "id"},{$addToSet: {field:
    {key2: v2, key1: v1}
    }});
    

    Mongo will see this as a duplicate and NOT this object to the array.

提交回复
热议问题