[英]Get multiple arrays of mongodb documents and merge them for unique values
我需要获取所有标签,这些标签存储在多个文档的数组中。 我可以通过以下方式选择所有需要的文件:
Collection.find({ 'metadata.tags': { $exists: true } });
第一个文档的数据可能看起来像
"metadata" : {
"type" : "photo",
"tags" : [
"test",
"anything",
"something",
"more"
]
}
第二个:
"metadata" : {
"type" : "photo",
"tags" : [
"different",
"content",
"something",
"more"
]
}
数组中的某些元素是重复的。 我只需要唯一的值,因此本示例中的结果将包含六个元素。
我会想到这样的东西来删除重复项:
var c = a.concat(b);
var tags = c.filter( function (item, pos) { return c.indexOf(item) == pos; } );
return tags;
但是我的第一个问题是如何访问所有数组,可能要多于两个数组,因为find()
会给我多个文档。 如何获取所有文档的数组并合并它们?
第二个问题是删除重复项,因为我的示例仅适用于两个数组。
更新资料
我会做这样的事情:
var tags = [];
Media.find({ 'metadata.tags': { $exists: true } }).forEach(function(doc) {
tags = tags.concat(doc.metadata.tags);
});
var result = tags.filter( function (item, pos) { return tags.indexOf(item) == pos; } );
return result;
也许可以优化...
为了解决您的问题,mongoDB已经向我们提供了一个distinct
命令。 如下使用它:
Collection.distinct('metadata.tags')
上面的命令将为您提供与数组不同的值。 不会有任何重复的元素。 因此,您的第二个问题也将得到解决
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.