How to access embedded documents in MongoTemplate when the key is an empty string?

376 views Asked by At
{
        "_id" : ObjectId("550add7ee0b4b54a3e7ad53c"),
        "day" : "14-03-2015",
        "node" : "2G",
        "nodeName" : "BLR_SGSN",
        "" : {
                "A" : 905.84,
                "B" : 261.34,
                "C" : 2103.94,
                "D" : 39.67
        }
}

I have this as my data in mongo. How do I get values of A,B,C,D. ??

1

There are 1 answers

0
AudioBubble On

You cannot query on this as the sub-document fields cannot be selected.

This can only be a result of a programming error doing something like this ( and probably trying to compute a key name in the process ):

db.collection.insert({
    "": {
        "A": 1,
        "B": 2,
        "C": 3
    }    
})

So you cannot get to sub-elements by standard query ways like:

db.collection.find({ ".A": 905.84 })

You can fix this by updating the documents in the collection affected in this way by giving them a proper key name. But it is of course this is an iterative process. Not sure how to fix this other than with JavaScript from the shell due to the naming problem but:

db.collection.find({ "": { "$exists": true } }).forEach(function(doc) { 
    if ( doc.hasOwnProperty("") ) { 
        doc.newprop = doc[""]; 
       delete doc[""]; 
       db.collection.update({ "_id": doc._id }, doc );
    }
})

Then at least you can access things by the new "newprop" key ( or whatever you call it ):

db.collection.find({ "newprop.A": 905.84 })

And the same sort of thing will work in other drivers.

My advice here is "go and fix this" and find out the code that caused this key name to be blank in the first place.

There should be a bug report submitted to the MongoDB core project as none of the dirvers handle this well. I thought I could even use $rename here, but you can't.

So blank "" keys are a problem that needs to be fixed.