djongo icon indicating copy to clipboard operation
djongo copied to clipboard

Getting incorrect mapping of key and value in resultset

Open kishudos opened this issue 8 years ago • 3 comments

Hi, I have a historical data in my mongoDB collections and I have written models for all to map. example doc in mongoDB collection:- "MyCollection"

  "_id": 2146767,
  "abc": 2146767,
  "abcd": 2353,
  "data": {
    "2012": {
      "1": {
        "key": "value"
      },
      "2": {
        "key": "value"
      }
    }
  },
  "xyz": 1,
  "pqr": 1203199,
  "name": "sonu"
}

Model :-

class ModelName(models.Model):
    abc = models.IntegerField()
    abcd = models.IntegerField()
    xyz = models.IntegerField()
    pqr = models.IntegerField()
    name = models.CharField()
    data = models.EmbeddedModelField(model_container=object)
    objects = models.DjongoManager()

    class Meta:
        db_table = "MyCollection"

But when I am writing query then I am getting incorrect order in result set.

r = ModelName.objects.all().values('abc', 'abcd', 'name','data') Resultset:- {'abc':2146767, 'abcd':OrderedDict(), 'name':sonu, 'data':2353} Here, value of 'abcd' and 'data' are getting swap, or in my real case it is unpridictable. Please help me , Thanks.

kishudos avatar May 25 '18 11:05 kishudos

@kishudos I encounter this issue very often. This occurs when I already have data in my mongo collection but I add another field in between the existing fields, and migrate. To fix this I use the following script to run after every migration/new field addition.

from bson.json_util import dumps, loads
from collections import OrderedDict
from django.db.models.fields.reverse_related import ManyToOneRel

def sync_mongo_field_order(model):
    all_records = loads(dumps(model.objects.mongo_find()))
    if not all_records:
        return
    field_order = [
            field.column for field in model._meta.get_fields()
            if not isinstance(field, ManyToOneRel)]
    fixed_records = []
    for record in all_records:
        record_dict = OrderedDict()
        record_dict['_id'] = record['_id']
        for field in field_order:
            record_dict[field] = record.get(field)
        fixed_records.append(record_dict)
    model.objects.mongo_delete_many({})
    model.objects.mongo_insert_many(fixed_records)

arindammanidas avatar May 30 '18 09:05 arindammanidas

This has been a huge miss on my part. Turns out MongoDB does NOT return the fields, in order of projection. while the returned document is an ordered dict, the order of the fields can get messed up during and after migrations. But I always thought mongoDB returned the fields based on how the projection (which is also an ordered dict).

There is a bug report filed for this very issue..

In the mean time I will release a workaround

nesdis avatar Jun 06 '18 04:06 nesdis

This issue has been fixed

nesdis avatar Jun 12 '18 02:06 nesdis