MongoDB如何将集合中的多个对象推送到数组中

MongoDB如何将集合中的多个对象推送到数组中,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,如果我在mongodb集合中有多个文档如下所示: // document 1 { _id: '123', date: '5/10/15', charges: [{ amount: 500, description: 'foo', },{ amount: 400, description: 'bar', }], } // document 2 { _id: '456',

如果我在mongodb集合中有多个文档如下所示:

// document 1
{
    _id: '123',
    date: '5/10/15',

    charges: [{
        amount: 500,
        description: 'foo',
    },{
        amount: 400,
        description: 'bar',
    }],
}


// document 2    
{
    _id: '456',
    date: '5/11/15',

    charges: [{
        amount: 500,
        description: 'foo',
    },{
        amount: 300,
        description: 'foo',
    }],
}
[{
    amount: 500,
    description: 'foo'
}, {
    amount: 500,
    description: 'foo'
}]
我想创建和数组的所有费用,有一个金额为500。结果应该如下所示:

// document 1
{
    _id: '123',
    date: '5/10/15',

    charges: [{
        amount: 500,
        description: 'foo',
    },{
        amount: 400,
        description: 'bar',
    }],
}


// document 2    
{
    _id: '456',
    date: '5/11/15',

    charges: [{
        amount: 500,
        description: 'foo',
    },{
        amount: 300,
        description: 'foo',
    }],
}
[{
    amount: 500,
    description: 'foo'
}, {
    amount: 500,
    description: 'foo'
}]
实现这一目标最有效的方法是什么?

试试以下方法:

db.collection.aggregate(
    [
        { 
            $unwind: "$charges"
        },
        {
            $match: {
                amount: 500
            }
        }
    ]
);

在与和一起使用的文档中:

db.collection.aggregate([
//将文档与所需的标准匹配
{“$match”:{“费用.金额”:500},
//展开以取消标准化内容
{“$unwind”:“$charges”},
//过滤非规范化文档
{“$match”:{“费用.金额”:500},
//分组返回结果
{“$组”:{
“_id”:空,
“费用”:{“$push”:“$charges”}
}}        
])
在现代版本中,更有效的方法是先过滤阵列:

db.collection.aggregate([
//将文档与所需的标准匹配
{“$match”:{“费用.金额”:500},
//对阵列进行预过滤
{“$redact”:{
“$cond”:{
“如果”:{“$eq”:[{“$ifNull”:[“$amount”,500]},500]},
“然后”:“$$down”,
“else”:“$$PRUNE”
}
}},
//展开以取消标准化内容
{“$unwind”:“$charges”},
//分组返回结果
{“$组”:{
“_id”:空,
“费用”:{“$push”:“$charges”}
}}        
])
未来版本(在当前开发版本中工作)将有一个更有用的
$filter
方法:

db.collection.aggregate([
//将文档与所需的标准匹配
{“$match”:{“费用.金额”:500},
//过滤阵列
{“$project”:{
“费用”:{
“$filter”:{
“输入”:“$charges”,
“作为”:“押记”,
“条件”:{
“$eq”:[“$$charge.amount”,500]
}
}
}
}},
//展开以取消标准化内容
{“$unwind”:“$charges”},
//分组返回结果
{“$组”:{
“_id”:空,
“费用”:{“$push”:“$charges”}
}}        
])
所有结果如下:

{
“_id”:空,
“费用”:[
{
金额:500,
描述:'foo'
}, {
金额:500,
描述:'foo'
}
]
}