美文网首页
Mongodb外层结构转内层

Mongodb外层结构转内层

作者: 陈文瑜 | 来源:发表于2019-10-07 15:21 被阅读0次

    插入语句

    db.resultsCollection.insert([
    { "timeStamp" : 1341834988666, "label" : "sharon", "responseCode" : "200", "value" : 10, "success" : "true"},
    { "timeStamp" : 1341834988696, "label" : "sharon", "responseCode" : "200", "value" : 35, "success" : "false"},
    { "timeStamp" : 1341834988676, "label" : "paul", "responseCode" : "200", "value" : 60, "success" : "true"},
    { "timeStamp" : 1341834988166, "label" : "paul", "responseCode" : "200", "value" : 40, "success" : "true"},
    { "timeStamp" : 1341834988686, "label" : "paul", "responseCode" : "404", "value" : 15, "success" : "true"},
    { "timeStamp" : 1341834988266, "label" : "paul", "responseCode" : "404", "value" : 99, "success" : "false"}
    ])
    

    查询

    db.sales.aggregate(
       [
         {
           $group:
             {
               _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
               itemsSold: { $push:  { item: "$item", quantity: "$quantity" } }
             }
         }
       ]
    )
    

    结果

    // 1
    {
        "_id": {
            "day": NumberInt("46"),
            "year": NumberInt("2014")
        },
        "itemsSold": [
            {
                "item": "abc",
                "quantity": 10
            },
            {
                "item": "xyz",
                "quantity": 10
            },
            {
                "item": "xyz",
                "quantity": 5
            },
            {
                "item": "xyz",
                "quantity": 10
            }
        ]
    }
    
    // 2
    {
        "_id": {
            "day": NumberInt("34"),
            "year": NumberInt("2014")
        },
        "itemsSold": [
            {
                "item": "jkl",
                "quantity": 1
            },
            {
                "item": "xyz",
                "quantity": 5
            }
        ]
    }
    
    // 3
    {
        "_id": {
            "day": NumberInt("1"),
            "year": NumberInt("2014")
        },
        "itemsSold": [
            {
                "item": "abc",
                "quantity": 2
            }
        ]
    }
    
    

    相关文章

      网友评论

          本文标题:Mongodb外层结构转内层

          本文链接:https://www.haomeiwen.com/subject/oatqyctx.html