Vahid Chakoshy
Vahid Chakoshy

Reputation: 1527

mongoengine embedded field update

this is my schema

class Url_per_date(EmbeddedDocument):
    date = DateTimeField()
    count = IntField(default=0)

class Daily_visit(Document):
    domain = StringField()
    count = IntField(default=0)
    per_date = ListField(EmbeddedDocumentField('Url_per_date'))

i have collection like this:

{
"_id" : ObjectId("51c97e685aa3b3414c7e406a"),
"_types" : "Daily_visit",
"count" : 1,
"domain" : "yahoo.com",
"per_date" : {
        "count" : 1,
        "date" : ISODate("2013-05-20T00:00:00Z")
    }
}

i need to update yahoo.com by date range. if per_date not have ISODate("2013-05-20T00:00:00Z") i need to create it, if i have it inc__count=1.

Upvotes: 0

Views: 624

Answers (2)

Scott Stafford
Scott Stafford

Reputation: 44828

In MongoEngine, embedded fields are referenced by replacing dot-notation with double underscores:

Fields on embedded documents may also be referred to using field lookup syntax by using a double-underscore in place of the dot in object attribute access syntax:

http://mongoengine-odm.readthedocs.org/en/v0.6.8/guide/querying.html#filtering-queries

Upvotes: 1

Mohammad Efazati
Mohammad Efazati

Reputation: 4930

at first your result must be like this

{
"_id" : ObjectId("51c97e685aa3b3414c7e406a"),
"_types" : "Daily_visit",
"count" : 1,
"domain" : "yahoo.com",
"per_date" : [{
        "count" : 1,
        "date" : ISODate("2013-05-20T00:00:00Z")
    }]
}

how create date? create new one for today and select database like this

today = datetime.today()
try:
    yahoo_obj = Daily_visit.objects.get(domain="yahoo.com", per_date__date=date)
    yahoo_obj.per_date[-1].count += 1
except:
    yahoo_obj = Daily_visit.objects.get(domain="yahoo.com")
    yahoo_obj.per_date = .... # just append new list

Upvotes: 0

Related Questions