2

I need to group these docs by taxonomy array but I've to exclude from group the "term3" item from the first Doc. (My situation is more complicated in a real app but this example fits.)

[
    {
        "_id": "1",
        "Taxonomy": [
            {
                "Key": "1", "Term": "term1"
            },
            {
                "Key": "2", "Term": "term2"
            },
            {
                "Key": "3", "Term": "term3"
            }
        ]
    },
    {
        "_id": "2",
        "Taxonomy": [
            {
                "Key": "1", "Term": "term1"
            },
            {
                "Key": "2", "Term": "term2"
            }
        ]
    },
    {
        "_id": "3",
        "Taxonomy": [
            {
                "Key": "1", "Term": "term1"
            },
            {
                "Key": "2", "Term": "term2"
            }
        ]
    }
]

This command generates two nodes due to the "term3" item:

{$group: {"_id" :"$Taxonomy","Posts" : { "$addToSet" : { "_id" : "$_id"}}}}

It is possible to unwind, match and then re-group documents or there is a simple way?

3
  • I'm not sure if this will work, but have you considered an $unwind -> $limit -> $group pipeline? Commented Aug 7, 2014 at 16:11
  • I cannot do this with a limit, I need almost to match... but I'm stuck with the syntax! Commented Aug 7, 2014 at 16:26
  • 1
    do you mean that you want to end up with exactly the same as above but you want to only have term1, term2 elements in the array left? In general, it's better to show us the result you want to have, in addition to what you have tried. Commented Aug 7, 2014 at 17:04

1 Answer 1

4

Running this aggregation:

db.terms.aggregate([
    {$unwind:"$Taxonomy"},
    {$match:{"Taxonomy.Term":{$ne:"term3"}}},
    {$group:{_id:"$_id",Taxonomy:{$push:"$Taxonomy"}}}
])

Will produce this result:

{ "_id" : "2", "Taxonomy" : [ { "Key" : "1", "Term" : "term1" }, { "Key" : "2", "Term" : "term2" } ] }
{ "_id" : "3", "Taxonomy" : [ { "Key" : "1", "Term" : "term1" }, { "Key" : "2", "Term" : "term2" } ] }
{ "_id" : "1", "Taxonomy" : [ { "Key" : "1", "Term" : "term1" }, { "Key" : "2", "Term" : "term2" } ] }

If you then need to do further grouping/processing, you can add more stages. If you needed to exclude based on Key rather than Term then you can adjust $match stage. If you want to exclude everything other than term1 and term2 you would change the $ne to be $in:[<list-of-values-to-keep>].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.