MongoAlchemy查询嵌入式文档 [英] MongoAlchemy query embedded documents

查看:116
本文介绍了MongoAlchemy查询嵌入式文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用MongoAlchemy进行嵌入式文档操作. 但是我没有找到关于这些的任何文件. 谁能给我一些帮助?

I want to know how to use MongoAlchemy about embeded docment operation. But I havn't find any documents about these. Can anyone give me some helps?

这是演示代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from flask import Flask
from flaskext.mongoalchemy import MongoAlchemy

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['MONGOALCHEMY_DATABASE'] = 'book'
db = MongoAlchemy(app)

class Comment(db.Document):
    user_id = db.StringField(db_field='uid')
    posted = db.StringField(db_field='posted')

class Book(db.Document):
    title = db.StringField()
    author = db.StringField()

    comments = db.ListField(db.DocumentField(Comment), db_field='Comments')

from mongoalchemy.session import Session
def test():
    with Session.connect('book') as s:
        s.clear_collection(Book)

    save()
    test_Book()

def save():
    title = "Hello World"
    author = 'me'

    comment_a = Comment(user_id='user_a', posted='post_a')
    comment_b = Comment(user_id='user_b', posted='post_b')
    comments = [comment_a, comment_b]

    book = Book(title=title, author=author, comments=comments)
    book.save()

def test_Book():
    book = Book.query.filter({'author':'me'}).first()
    comment = book.comments[0]
    comment.posted = str(book.comments[0].posted)+'_new'
    book.save()
    print 'change posted: Book.comments[0].posted:', book.comments[0].posted

    comment_c = Comment(user_id='user_c', posted='post_c')
    book.comments.append(comment_c)
    book.save()
    print 'append: Book.comments[2].posted:', book.comments[2].posted

    query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}}).limit(1).first()
    print 'query type:', type(query)

if __name__ == '__main__':
    test()

  1. 我想查询user_id为"user_c"的数据,并只返回一个注释,我该怎么做? 下面的这些方法是否建议使用MongoAlchemy?顺便说一句,这些方法将返回整个文档.

  1. I want to query data which user_id is "user_c", and just return back one Comment, How can I do that? Does these methods below are MongoAlchemy remommended? BTW, these methods will return the whole document.

#query = Book.query.filter({Book.comments:{'uid':'user_c'}}).limit(1).first()
#query = Book.query_class(Comment).filter(Comment.user_id == 'user_c').limit(1).first()
#query = Book.query.filter({'comments':{'$elemMatch':{'uid':'user_c'}}}).limit(1).first()
#query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}}).limit(1).first()

  • 如何将通过查询找到的"user_c"更改为"user_c_new"?

  • How can I change "user_c" to "user_c_new" which find by query ?

    推荐答案

    Mongo不支持返回子文档.您可以使用$ elemMatch进行过滤,以便仅返回具有匹配属性的文档,但是您必须自己获取注释.您可以通过仅返回注释字段来进行稍微优化,如下所示:

    Mongo doesn't support returning subdocuments. You can use $elemMatch to filter so that only documents with matching attributes are returned, but you'll have to grab the comments yourself. You could slightly optimize by only returning the comments field as follows:

    query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}})
    query = query.fields(Book.comments.elem_match({Comment.user_id:'user_c'}))
    result = query.limit(1).first()
    print 'query result:', result.comments
    

    请注意,直到0.14.3(我刚刚在几分钟前发布)中存在此错误,否则将导致result.comments无法正常工作.

    Note that there was a bug with this up until 0.14.3 (which I just released a few minutes ago) which would have caused results.comments not to work.

    另一个非常重要的提示:我在此处执行的elem_match仅返回第一个匹配元素.如果想要所有匹配的元素,则必须自己过滤它们:

    Another very important note is that the elem_match I'm doing there only returns the first matching element. If you want all matching elements you have to filter them yourself:

    query = Book.query.filter({Book.comments:{'$elemMatch':{Comment.user_id:'user_c'}}})
    result = query.limit(1).first()
    print 'query result:', [c for c in result.comments if c.user_id == 'user_c']
    

    这篇关于MongoAlchemy查询嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆