从子文档数组中删除数组元素

时间:2014-12-10 14:21:29

标签: mongodb pymongo

{
"_id" : ObjectId("5488303649f2012be0901e97"),
"user_id":3,
"my_shopping_list" : {
    "books" : [ ]
},
"my_library" : {
    "books" : [
        {
            "date_added" : ISODate("2014-12-10T12:03:04.062Z"),
            "tag_text" : [
                "english"
            ],
            "bdata_product_identifier" : "a1",
            "tag_id" : [
                "fa7ec571-4903-4aed-892a-011a8a411471"
            ]
        },
        {
            "date_added" : ISODate("2014-12-10T12:03:08.708Z"),
            "tag_text" : [
                "english",
                "hindi"
            ],
            "bdata_product_identifier" : "a2",
            "tag_id" : [
                "fa7ec571-4903-4aed-892a-011a8a411471",
                "60733993-6b54-420c-8bc6-e876c0e196d6"
            ]
        }
    ]
},
"my_wishlist" : {
    "books" : [ ]
},

}

在此,我想使用englishtag_text的每个my_library数组中仅删除only user_id and tag_text此文档属于user_id:3。我已经尝试了一些删除整本书子文档的查询。谢谢。

2 个答案:

答案 0 :(得分:1)

一种可能的解决方案是重复

db.collection.update({user_id: 3, "my_library.books.tag_text": "english"}, {$pull: {"my_library.books.$.tag_text": "english"}}

直到MongoDB无法再匹配要更新的文档。

答案 1 :(得分:1)

好吧,因为您使用pymongomongodb并没有提供一种很好的方法,因为使用$运算符只会从english中提取english第一个子文档,为什么不编写一个脚本,从每个tag_text删除>>> doc = yourcollection.find_one( { 'user_id': 3, "my_library.books" : {"$exists": True}}, {"_id" : 0, 'user_id': 0 }) >>> books = doc['my_library']['books'] #books field in your doc >>> new_books = [] >>> for k in books: ... for x, y in k.items(): ... if x == 'tag_text' and 'english' in y: ... y.remove('english') ... new_book.append({x:y}) ... >>> new_book [{'tag_text': []}, {'tag_id': ['fa7ec571-4903-4aed-892a-011a8a411471']}, {'bdata_product_identifier': 'a1'}, {'date_added': datetime.datetime(2014, 12, 10, 12, 3, 4, 62000)}, {'tag_text': ['hindi']}, {'tag_id': ['fa7ec571-4903-4aed-892a-011a8a411471', '60733993-6b54-420c-8bc6-e876c0e196d6']}, {'bdata_product_identifier': 'a2'}, {'date_added': datetime.datetime(2014, 12, 10, 12, 3, 8, 708000)}] >>> yourcollection.update({'user_id' : 3}, {"$set" : {'my_library.books' : bk}}) ,然后更新您的文档。

<强>演示:

>>> yourcollection.find_one({'user_id' : 3})
{'user_id': 3.0, '_id': ObjectId('5488303649f2012be0901e97'), 'my_library': {'books': [{'tag_text': []}, {'tag_id': ['fa7ec571-4903-4aed-892a-011a8a411471']}, {'bdata_product_identifier': 'a1'}, {'date_added': datetime.datetime(2014, 12, 10, 12, 3, 4, 62000)}, {'tag_text': ['hindi']}, {'tag_id': ['fa7ec571-4903-4aed-892a-011a8a411471', '60733993-6b54-420c-8bc6-e876c0e196d6']}, {'bdata_product_identifier': 'a2'}, {'date_added': datetime.datetime(2014, 12, 10, 12, 3, 8, 708000)}]}, 'my_shopping_list': {'books': []}, 'my_wishlist': {'books': []}}

检查一切是否正常。

{{1}}