vijay shanker vijay shanker - 5 months ago 50
Bash Question

How to set ReferenceField value of mongoengine in mongodb shell?

this is my 2nd day with mongo. I am working with django + mongoengine.
structure of my article document is like this:

class Article(Document):
title = StringField(required=True)
content = StringField(required=True)
comments = ListField(ReferenceField(Comment))
author = ReferenceField(MUser, required=False)


I can set value of author from django shell, but i cant find a way to set this author field value (which will be a MUser object).
I have tried this:

db.article.update({
'title' : 'asdasdasdasd'
}, {
$set : {
'author' : db.m_user.find({
'email' : 'vsp@gmail.com'
})
}
})


but this does something that i dont get, when i do
db.article.find()
i get this result:

{
"_id" : ObjectId("57153cc2aec9680bc327bedb"),
"title" : "asdasdasdasd",
"content" : "",
"author" : {
"_mongo" : {
"slaveOk" : false,
"host" : "127.0.0.1",
"defaultDB" : "",
"promptPrefix" : "",
"authStatus" : {
"authRequired" : true,
"replSetGetStatus" : false,
"isMaster" : true
},
"_readMode" : "commands",
"_writeMode" : "commands"
},
"_db" : {
"_mongo" : {
"slaveOk" : false,
"host" : "127.0.0.1",
"defaultDB" : "",
"promptPrefix" : "",
"authStatus" : {
"authRequired" : true,
"replSetGetStatus" : false,
"isMaster" : true
},
"_readMode" : "commands",
"_writeMode" : "commands"
},
"_name" : "mblog"
},
"_collection" : {
"_mongo" : {
"slaveOk" : false,
"host" : "127.0.0.1",
"defaultDB" : "",
"promptPrefix" : "",
"authStatus" : {
"authRequired" : true,
"replSetGetStatus" : false,
"isMaster" : true
},
"_readMode" : "commands",
"_writeMode" : "commands"
},
"_db" : {
"_mongo" : {
"slaveOk" : false,
"host" : "127.0.0.1",
"defaultDB" : "",
"promptPrefix" : "",
"authStatus" : {
"authRequired" : true,
"replSetGetStatus" : false,
"isMaster" : true
},
"_readMode" : "commands",
"_writeMode" : "commands"
},
"_name" : "mblog"
},
"_shortName" : "m_user",
"_fullName" : "mblog.m_user"
},
"_ns" : "mblog.m_user",
"_query" : {
"email" : "vsp@gmail.com"
},
"_fields" : null,
"_limit" : 0,
"_skip" : 0,
"_batchSize" : 0,
"_options" : 0,
"_cursor" : null,
"_numReturned" : 0,
"_special" : false
}
}


I managed to set similar situation from django shell, and that record shows neatly what author is , like this..

{
"_id" : ObjectId("57153ae9aec9680a8ae8f5a6"),
"title" : "sdd",
"content" : "eer",
"author" : ObjectId("576fff2daec96854d8bff581"),
"comments" : [ObjectId("5770282faec968640568f4ce")]
}


How do i achieve this. Thanks

Answer

In Mongo shell we cannot use sub-queries in a kind os SQL like syntax.

To solve that we could do:

var author = db.m_user.find({
        'email' : 'vsp@gmail.com'
    }).limit(1).toArray()

    db.article.update({
        'title' : 'asdasdasdasd'
    }, {
        $set : {
            'author' : author[0]._id
        }
    })

Any comments welcome!