2013-11-28 257 views
0

我想知道如何使用MongoAlchemy關於嵌入式文檔操作。 但我沒有找到任何有關這些文件。 任何人都可以給我一些幫助嗎?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 remommended?順便說一句,這些方法將返回整個文檔。

    #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」的評論?

回答

1

Mongo不支持返回的子文檔。您可以使用$ elemMatch進行過濾,以便只返回具有匹配屬性的文檔,但您必須自己獲取註釋。

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.comments:您可以通過僅如下返回意見欄略微優化不工作。

另一個非常重要的筆記是我在那裏做的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'] 
+0

謝謝!謝謝你的幫忙! – user2089487