Getting a distinct aggregation of an array field across indexes

后端 未结 5 1531
[愿得一人]
[愿得一人] 2020-12-03 03:10

I\'m trying to learn MongoDB and how it\'d be useful for analytics for me. I\'m simply playing around with the JavaScript console available on their website and have created

5条回答
  •  Happy的楠姐
    2020-12-03 03:48

    You can use the aggregation framework. Depending on how you'd like the results structured, you can use either

    var pipeline = [ 
            {"$unwind": "$tags" } ,
            { "$group": { _id: "$tags" } }
        ];
    R = db.tb.aggregate( pipeline );
    printjson(R);
    
    {
            "result" : [
                    {
                            "_id" : "seventy"
                    },
                    {
                            "_id" : "ten"
                    },
                    {
                            "_id" : "sixty"
                    },
                    {
                            "_id" : "thirty"
                    },
                    {
                            "_id" : "twenty"
                    }
            ],
            "ok" : 1
    }
    

    or

    var pipeline = [ 
            {"$unwind": "$tags" } ,
            { "$group": 
                { _id: null, tags: {"$addToSet": "$tags" }  }
            }
        ];
    R = db.tb.aggregate( pipeline );
    printjson(R);
    
    {
            "result" : [
                    {
                            "_id" : null,
                            "tags" : [
                                    "seventy",
                                    "ten",
                                    "sixty",
                                    "thirty",
                                    "twenty"
                            ]
                    }
            ],
            "ok" : 1
    }
    

提交回复
热议问题