在MongoDB中计算模型数组中的唯一值 [英] Count unique values within model's Array in MongoDB

查看:86
本文介绍了在MongoDB中计算模型数组中的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多个模型的数组中仅对唯一值进行计数的最佳方法是什么?假设我的模型是这样的:

What is the best way to just COUNT unique values within many model's array? Let's say my Model is like this:

{
  myKey: [
    "idnumber1000",
    "idnumber1001",
    "idnumber1005",
  ]
}

我大约有10.000,但是myKey的值不同.我想知道,对于给定的集合,我有多少个不同的值.

And that I have about 10.000 of them, but with different values for myKey. I want to know, how many DIFFERENT values I have for a given set of collection.

我最初的想法是将所有模型加载到内存中,然后使用Node.js进行计算.但是由于我的数据集会增长很多(大约30-50K),所以这会占用我的计算机大量的内存.这是唯一的做做方法,还是还有另一种方法?

My initial idea was to load ALL models in memory, and then, compute that with Node.js. But as my data set can grow a lot (about 30-50K), that would consume a lot of memory in my machine. Is this the only way to doit, or is there another?

我将Mongoose与Node.js结合使用

I'm using Mongoose with Node.js

推荐答案

您可以使用简单的aggregate管道进行此操作:

You can do this with a simple aggregate pipeline:

MyModel.aggregate([
    // Project just the myKey field as that's all that's needed
    {$project: {_id: 0, myKey: 1}},
    // Duplicate each doc, once per myKey element
    {$unwind: '$myKey'},
    // Group on myKey and get a count
    {$group: {_id: '$myKey', count: {$sum: 1}}}
  ],
  function(err, results) {...}
);

这篇关于在MongoDB中计算模型数组中的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆