Question

For Example.. In Mongodb..

> db.test.findOne({}, {'mapField.FREE':1})
{
    "_id" : ObjectId("4fb7b248c450190a2000006a"),
    "mapField" : {
            "BOXFLUX" : {
                    "a" : "f",
            }
    }
}

The 'mapField' field is made of MapField of Mongoengine. and 'mapField' field has a log of key and data.. but I just retrieved only 'BOXFLUX'..

this query is not working in MongoEngine.... for example..

BoxfluxDocument.objects( ~~ querying ~~ ).only('mapField.BOXFLUX')

AS you can see.. only('mapField.BOXFLUX') or only only('mapField__BOXFLUX') does not work. it retrieves all 'mapField' data, including 'BOXFLUX' one..

How can I retrieve only a field of MapField???

Was it helpful?

Solution

I see there is a ticket for this: https://github.com/hmarr/mongoengine/issues/508

Works for me heres an example test case:

def test_only_with_mapfields(self):

    class BlogPost(Document):
        content = StringField()
        author = MapField(field=StringField())

    BlogPost.drop_collection()

    post = BlogPost(content='Had a good coffee today...', 
                    author={'name': "Ross", "age": "20"}).save()

    obj = BlogPost.objects.only('author__name',).get()

    self.assertEquals(obj.author['name'], "Ross")
    self.assertEquals(obj.author.get("age", None), None)

OTHER TIPS

Try this:

query = BlogPost.objects({your: query})
if name:
    query = query.only('author__'+name)
else:
    query = query.only('author')

As always, Ross Really Thanks a lot!!!!!!!!!

I found my fault.. that is.. I used 'only' twice..

For example,

BlogPost.objects.only('author').only('author__name') 

something like this..

I spent a whole day finding out what is wrong with Mongoengine..

so.. my dumb conclusion was...

BlogPost.objects()._collection.find_one(~~ filtering query ~~, {'author.'+ name:1})

something like this..

but as you know it's a just raw data not a mongoengine query..

after this code, I cannot run any mongoengine methods...

Anyway..

In my case, I should have to query depending on some conditions.

so it will be great that 'only' method overwrites 'only' methods written before.. In my humble opinion.

I hope this feature would be integrated with next version..

Right now, I have to code duplicate code.. for example..

not this code...

query = BlogPost.objects()
query( query~~).only('author')
if name:
    query = query.only('author__'+name)

this code

query = BlogPost.objects()
query( query~~).only('author')
if name:
    query = BlogPost.objects().only('author__'+name)

so.. I think.. the second one looks dirtier than first one.

of course, the first code shows you all all data using "only('author')" not "only('author__name')

Thanks A LOT!!!!!!!!!

Ross, you saved me!!! Thanks.. (I thought Mongoengine could not simply do those queries.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top