如何在mongodb中获取数组中对象的值?

时间:2019-05-16 10:04:59

标签: python mongodb

我想在price为1的文档数组中获取quantity_id为3的对象。

{
   _id: 0,
   items: [
     { item_id: 43, quantity: 2, price: 10 },
     { item_id: 2, quantity: 1, price: 240 }
   ]
}
{
   _id: 1,
   items: [
     { item_id: 23, quantity: 3, price: 110 },
     { item_id: 103, quantity: 3, price: 5 },
     { item_id: 38, quantity: 2, price: 300 }
   ]
}
{
    _id: 2,
    items: [
       { item_id: 4, quantity: 1, price: 23 }
    ]
}
{
   _id: 3,
   items: [
     { item_id: 1241, quantity: 5, price: 13213 },
     { item_id: 4321, quantity: 6, price: 43214 },
     { item_id: 12341, quantity: 72, price: 12414 }
   ]
}
{
   _id: 4,
   items: [
     { item_id: 1241, quantity: 5, price: 13213 },
     { item_id: 4321, quantity: 6, price: 43214 },
     { item_id: 12341, quantity: 72, price: 12414 }
   ]
}
{
   _id: 5,
   items: [
     { item_id: 1241, quantity: 5, price: 13213 },
     { item_id: 4321, quantity: 6, price: 43214 },
     { item_id: 12341, quantity: 72, price: 12414 }
   ]
}

我该怎么办?

1 个答案:

答案 0 :(得分:0)

db.collname.aggregate([
    {'$match':{'_id':'1'}},
    {'$project':{
        "price":{
            '$filter':{
                'input':'$items',
                'cond':{'$eq':['$$this.quantity',3]}
            }
        }
    }}
])