精美的重复子项列表 [英] elegant list of repeated sub-items

查看:54
本文介绍了精美的重复子项列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用MongoDB将路径投影转换为单个数组?

How to transform a path projection into a single array with MongoDB?

使用真实数据,导入此 datapackage.json

Using real data, importing this datapackage.json by

wget -c https://raw.githubusercontent.com/datasets/language-codes/master/datapackage.json

mongoimport -d lang_db -c lang_meta datapackage.json --jsonArray

假设我需要一个资源中使用的所有媒体类型的列表,然后重复...因此,最简单的语法db.lang_meta.distinct("resources.mediatype")不能解决此问题...

suppose that I need a list of all mediatypes used in the resources, repeating... So the simplest syntax db.lang_meta.distinct("resources.mediatype"), is not a solution to this propblem...

db.lang_meta.find({},{"resources.mediatype":1}).pretty()不会产生单个列表,而是一个复杂的对象,

And db.lang_meta.find({},{"resources.mediatype":1}).pretty() not produces a single list, but a complex object,

{"_id" : ObjectId("56011be94564569fc920eda4"),
"resources" : [
    {
        "mediatype" : "text/csv"
    },
    {
        "mediatype" : "text/csv"
    },
    {
        "mediatype" : "text/csv"
    },
    {
        "mediatype" : "text/csv"
    }
]}

为降低复杂性,我们可以尝试map()

to reduce complexity we can try map(),

var aux = db.lang_meta.find().map(function(c) {
    var ret = [];
    for (var i=0; i<c.resources.length; i++) 
             ret.push( c.resources[i].mediatype );
   return ret;
});
var solution = aux[0];

但是它并不优雅(!)... mongoDB 中有一种简单的语法可以做到这一点?

but it is not elegant (!)... There are a simple syntax in mongoDB to do this?

此问题与其他问题/解决方案相关.

推荐答案

使用

Use $map in aggregation like this :

db.collection.aggregate({"$project":{"resources":{"$map":{"input":"$resources","as":"el","in":"$$el.mediatype"}}}})

这篇关于精美的重复子项列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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