我可以根据多个文件进行查询吗?

时间:2012-10-16 08:40:12

标签: mongodb

我有一个文档集合,其中每个文档都应该有另一个匹配的文档。 (这不是设计,仅适用于我当前的操作。)但是,集合中文档数量的当前计数是奇数。有没有办法可以查询一个未被另一个文档共享的密钥值?

即。如果我有这样的集合:

{_id:'dcab0001', foo: 1, bar: 'dfgdgd'}
{_id:'dcab0002', foo: 2, bar: 'tjhttj'}
{_id:'dcab0003', foo: 1, bar: 'ydgdge'}
{_id:'dcab0004', foo: 3, bar: 'jyutkf'}
{_id:'dcab0005', foo: 3, bar: 'pofsth'}

我可以对foo进行查询,该查询将返回ID为dcab0002的文档。

1 个答案:

答案 0 :(得分:3)

您可以使用MapReduce或使用Aggregation Framework在MongoDB 2.2+中执行此操作。

以下是使用聚合框架的示例:

db.pairs.aggregate(

    // Group by values of 'foo' and count duplicates
    { $group: {
        _id: '$foo',
        key: { $push: '$_id' },
        dupes: { $sum: 1 }
    }},

    // Find the 'foo' values that are unpaired (odd number of dupes)
    { $match: {
        dupes: { $mod: [ 2, 1 ] }
    }}

    // Optionally, could add a $project to tidy up the output
)

示例输出:

{
    "result" : [
        {
            "_id" : 2,
            "key" : [
                "dcab0002"
            ],
            "dupes" : 1
        }
    ],
    "ok" : 1
}
相关问题