0

I'm trying to make an insert into pymongo collection via code and for some reason the inserts are going in random order. For the data below, the documents have the 'records' in reverse order. When I do a db.collection.find(), I notice they are inserted in '003', '002', '001' rather than the other way around:

[
{
    "jobs": {
        "AA": {
            "name": "AA",
            "records":{
                "001": {
                    "name": "001"
                },
                "002": {
                    "name": "002"
                },
                "003": {
                    "name": "003"
                }
            }
        },
        "AB": {
            "name": "AB",
            "records":{
                "001": {
                    "name": "001"
                },
                "002": {
                    "name": "002"
                },
                "003": {
                    "name": "003"
                }
            }
        },
    },
},

]

Here is my code for insertion:

JOBS_FIXTURES = json.load(open('./tests/temp.json', 'r'))
        self.client = MongoClient(MONGO_URL)
        db = self.client.test_datasource
        self.jobs_collection = db.jobs
        self.jobs_collection.remove()
        self.jobs_collection.insert(JOBS_FIXTURES)

I checked out the insert api here: https://docs.mongodb.com/manual/reference/method/db.collection.insert/ and there is no obvious reason why it messes the order up as by default it's supposed to be ordered.

The pymongo version I'm using is 2.6.2.

Any help? Thanks!

falc0nit3
  • 999
  • 2
  • 8
  • 16
  • JSON is unordered, just like a Python dictionary. What specifically have you done that makes you think it should be ordered? – roganjosh Jun 24 '17 at 19:37
  • I actually don't know the Mongo implementation but it's possible that records are randomly ordered before they are inserted, and the retreived object might also be randomly ordered... whether there's a set format in how it's physically stored, I'm not sure. – roganjosh Jun 24 '17 at 19:40
  • If the sub-document field's order matter then you should consider take a look at [`SON`](http://api.mongodb.com/python/current/api/bson/son.html) however I will suggest you make records an array of sub-documents because dynamic fields are difficult to work with unless you are dealing with time series data or something like that. Also as @roganjosh pointed out, this is not specific to MongoDB – styvane Jun 24 '17 at 21:43

0 Answers0