最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongodb aggregation, Use value from a variable in the expression of $group _id - Stack Overflow

programmeradmin1浏览0评论

I am trying to groups documents by two fields, field1 and field2.

myCollection.aggregate([{
  $group: {
    _id: {
      group1: "$field1",
      group2: "$field2"
    },
    count: {
      $sum: 1
    }
  }
}])

Which works fine producing the expected results.

But I want to re run the above in a loop, each run will have different $field2, so the following is failing, how can I it be done? Thanks

const field3 = 'someValue';  // <<--- will change in every loop run ---

myCollection.aggregate([{
  $group: {
    _id: {
      group1: "$field1",
      group2: "$$field3"  //<<---------------- 
    },
    count: {
      $sum: 1
    }
  }
}])

I am trying to groups documents by two fields, field1 and field2.

myCollection.aggregate([{
  $group: {
    _id: {
      group1: "$field1",
      group2: "$field2"
    },
    count: {
      $sum: 1
    }
  }
}])

Which works fine producing the expected results.

But I want to re run the above in a loop, each run will have different $field2, so the following is failing, how can I it be done? Thanks

const field3 = 'someValue';  // <<--- will change in every loop run ---

myCollection.aggregate([{
  $group: {
    _id: {
      group1: "$field1",
      group2: "$$field3"  //<<---------------- 
    },
    count: {
      $sum: 1
    }
  }
}])
Share Improve this question edited Sep 28, 2016 at 8:10 DAXaholic 35.6k6 gold badges82 silver badges77 bronze badges asked Sep 27, 2016 at 22:02 Fred J.Fred J. 6,04913 gold badges60 silver badges113 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

The following should work for you

var field3  = 'someValue';
myCollection.aggregate([{
  $group: {
    _id: {
      group1: "$field1",
      group2: "$" + field3,
    },
    count: {
      $sum: 1
    }
  }
}])

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论