Stuart P. Bentley
Stuart P. Bentley

Reputation: 10675

Can I do a query based on multiple documents?

I have a collection of documents where every document should have another, matching document. (This isn't by design, only for my current operation.) However, the current count for the number of documents in the collection is an odd number. Is there a way I can do a query on values of a key that aren't shared by one other document?

ie. if I have a collection like this:

{_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'}

I could do a query on foo that would return back the document with id dcab0002.

Upvotes: 1

Views: 105

Answers (1)

Stennie
Stennie

Reputation: 65333

You could do this with MapReduce, or in MongoDB 2.2+ using the Aggregation Framework.

Here's an example using the Aggregation Framework:

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
)

Sample output:

{
    "result" : [
        {
            "_id" : 2,
            "key" : [
                "dcab0002"
            ],
            "dupes" : 1
        }
    ],
    "ok" : 1
}

Upvotes: 3

Related Questions