質問

Assuming I have the following JSON structure I want to group by gender and want to return multiple document values on in the same field:

[
    {
        "id": 0,
        "age": 40,
        "name": "Tony Bond",
        "gender": "male"
    },
    {
        "id": 1,
        "age": 30,
        "name": "Nikki Douglas",
        "gender": "female"
    },
    {
        "id": 2,
        "age": 23,
        "name": "Kasey Cardenas",
        "gender": "female"
    },
    {
        "id": 3,
        "age": 25,
        "name": "Latasha Burt",
        "gender": "female"
    }
] 

Now I know I can do something like this but I need to join both age and name into one field

.aggregate().group({ _id:'$gender', age: { $addToSet: "$age" }, name: { $addToSet: "$name"}})
役に立ちましたか?

解決

Yes you can, just have a sub-document as the argument:

db.collection.aggregate([
    { "$group": {
        "_id": "$gender",
        "person": { "$addToSet": { "name": "$name", "age": "$age" } }
    }}
])

Of course if you actually expect no duplicates here the $push does the same thing:

db.collection.aggregate([
    { "$group": {
        "_id": "$gender",
        "person": { "$push": { "name": "$name", "age": "$age" } }
    }}
])

他のヒント

In addition to what Neil mentioned for the aggregation query, you have to consider the fact that the document that contains the grouped individual record cannot be beyond 16 MB (in v2.5+) or the entire aggregate result cannot be more than 16MB (on v2.4 and below).

So in case you have huge data set, you have to be aware of limitations that may impose on the model you use to aggregate data.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top