【问题标题】:MongoAlchemy query embedded documentsMongoAlchemy 查询嵌入文档
【发布时间】:2013-11-28 11:41:36
【问题描述】:

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

这里是演示代码:

#!/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 推荐的吗?顺便说一句,这些方法将返回整个文档。

    #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()
    
  2. 如何将“user_c”更改为通过查询找到的“user_c_new”?

  3. 如何删除一条 user_id 为“user_b”的评论?

【问题讨论】:

    标签: mongodb mongoalchemy


    【解决方案1】:

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

    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(我几分钟前刚刚发布)之前存在一个错误,这会导致 results.cmets 无法工作。

    另一个非常重要的说明是我在那里做的 elem_match 只返回第一个匹配元素。如果你想要所有匹配的元素,你必须自己过滤它们:

    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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-22
      • 2012-08-26
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 2021-02-21
      相关资源
      最近更新 更多