【问题标题】:Group by in mongoose gives multiple recordGroup by in mongoose 提供多条记录
【发布时间】:2015-10-18 09:58:57
【问题描述】:

我正在尝试通过以下代码在猫鼬中通过聚合应用组

app.get('/api/get_conversation_all_carer/:carer_id',function(req,res){
        //Sender = user and receiver = carer
        var data = [];
        var conversation = {status_code:200, data:data};
        Conversation.find({'receiver_id': req.params.carer_id},{sender_id:1},{'group': 'sender_id'},function(err,result)
        {
            console.log(result);
        });
    });

这给了我以下输出

[{ _id: 561f985439365e3c2aa9398a,
    sender_id: '55f000a2878075c416ff9879' },
  { _id: 5620cfd0e4b0b1432a7331bb,
    sender_id: '55f000a2878075c416ff9879' }]

这里是相同的 sender_id 为什么我会得到两个单独的记录。
我只想要 sender_id 之类的
[{sender_id: '55f000a2878075c416ff9879'}]

【问题讨论】:

  • 我通常将group 视为$group。你确定'group' 是正确的吗?
  • 是的。实际上我没有收到任何语法错误

标签: node.js mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您想要.aggregate(),它是一个现代版本,可以在本机代码中更好地进行文档操作,而无需执行 JavaScript 或翻译。我怀疑您已经在文档中找到了$group,但没有意识到它与.aggregate() 相关联,而不是.find() 方法:

Conversation.aggregate(
    [
        { "$match": { "receiver_id": req.params.carer_id },
        { "$group": { "_id": "$sender_id" } }
    ],
    function(err,result) {
        console.log(result);
    }
);

这将为 $group 的“键”_id 中引用的字段的不同值返回一组结果,(即使只有一个)如下所示:

[{_id: '55f000a2878075c416ff9879'}]

您可以选择使用$project_id 交换为sender_id,但这不是一个好习惯,而只是让您的接收逻辑接受“唯一密钥”始终命名为_id

【讨论】:

    【解决方案2】:

    尝试使用db.collection.group()

    Conversation.collection.group(
    {
        key: {sender_id:1},
        cond: {receiver_id: req.params.carer_id},
        reduce: function ( curr, result ) { },
        initial: { },
        function(err, results){
            console.log(result);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 2020-02-17
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多