从mongoengine中删除嵌入文档中的值

时间:2012-09-26 09:40:46

标签: python mongodb cherrypy mongoengine

我有一个名为login_info的文档,其中包含以下字段:

class login_info(Document):
    user_name = StringField(max_length=120)
    password = StringField(max_length=120)
    email = EmailField()
    gender = StringField(max_length=120)
    date_of_birth = DateTimeField()
    visibility  = StringField(max_length=120)
    client_id = ObjectIdField(required=False)
    location = ListField(EmbeddedDocumentField("Tracking"))`

在上述字段中,location是一个嵌入式文档,其中包含以下字段:

  • 时间

  • 纬度,

  • 经度

我想删除此嵌入式文档中满足以下条件的值。

time < system_datetime

以下是login_info文档中的示例数据:

{
    "_cls":"login_info",
    "_id":ObjectId("5046f43c12d0592e3f59e25d"),
    "_types":[
        "login_info"
    ],
    "date_of_birth":ISODate("2011-02-07T00:00:00 Z"),
    "email":"jack@gmail.com",
    "expire":1346827684,
    "gender":"male",
    "issue":1346827324,
    "key":"47d1e64e51dfa1cf99ce4a59e0c940",
    "location":[
        {
            "Latitude":"5615.3111",
            "_types":[
                "Tracking"
            ],
            "_cls":"Tracking",
            "Longitude":"1236.711",
            "time":ISODate("2012-09-13T12:24:36.051 Z")
        },
        {
            "Latitude":"000",
            "_types":[
                "Tracking"
            ],
            "_cls":"Tracking",
            "Longitude":"3.70",
            "time":ISODate("2012-09-25T18:30:57.756 Z")
        },
        {
            "Latitude":"11",
            "_types":[
                "Tracking"
            ],
            "_cls":"Tracking",
            "Longitude":"1",
            "time":ISODate("2012-09-26T10:25:29.157 Z")
        },
        {
            "Latitude":"11",
            "_types":[
                "Tracking"
            ],
            "_cls":"Tracking",
            "Longitude":"1",
            "time":ISODate("2012-09-26T10:40:58.895 Z")
        },
        {
            "Latitude":"11",
            "_types":[
                "Tracking"
            ],
            "_cls":"Tracking",
            "Longitude":"1",
            "time":ISODate("2012-09-26T10:54:08.361 Z")
        },
        {
            "Latitude":"11",
            "_types":[
                "Tracking"
            ],
            "_cls":"Tracking",
            "Longitude":"1",
            "time":ISODate("2012-09-26T11:08:55.873 Z")
        }
    ],
    "password":"jack",
    "refresh_token":"22580a8f69",
    "token":"bac8a5f863",
    "user_name":"jack",
    "visibility":"visible"
}

1 个答案:

答案 0 :(得分:3)

如果您想使用MongoEngine从location文档中删除单个login_info嵌入文档,请执行以下操作:

// add 
loc1 = Tracking( time=datetime(2011, 11, 5, 0, 0, 0) )
loc2 = Tracking( time=datetime(2012, 10, 5, 0, 0, 0) )

login = login_info( user_name='Mark', location=[loc1, loc2] )
login.save()

// remove locations from the location list
login.objects( title=user_name='Mark' ).update_one( pull__lt=datetime.now() )

注意:mongoengine 0.7.5有一个bug,所以你必须从https://github.com/MongoEngine/mongoengine下载最新版本