简体   繁体   English

mongoexport csv输出最后一个数组值

[英]mongoexport csv output last array values

Inspired by this question in Server Fault https://serverfault.com/questions/459042/mongoexport-csv-output-array-values 在服务器故障中受此问题启发https://serverfault.com/questions/459042/mongoexport-csv-output-array-values

I'm using mongoexport to export some collections into CSV files, however when I try to target fields which are the last members of an array I cannot get it to export correctly. 我正在使用mongoexport将某些集合导出到CSV文件中,但是当我尝试定位作为数组最后一个成员的字段时,我无法使其正确导出。

Command I'm using 我正在使用的命令

mongoexport -d db -c collection -fieldFile fields.txt --csv > out.csv

One item of my collection: 我的收藏中的一件:

{
    "id": 1,
    "name": "example",
    "date": [
        {"date": ""},
        {"date": ""},
    ],
    "status": [
         "true",
         "false",
    ],
}

I can access to the first member of my array writing the fields like the following 我可以访问写入数组的第一个成员,如下所示:

name
id
date.0.date
status.0

Is there a way to acess the last item of my array without knowing the lenght of the array? 有什么方法可以在不知道数组长度的情况下访问数组的最后一项吗?

Because the following doesn't work: 因为以下操作无效:

name
id
date.-1.date
status.-1

Any idea of the correct notation? 对正确的符号有任何想法吗? Or if it's simply not possible? 还是根本不可能呢?

It's not possible to reference the last element of the array without knowing the length of the array, since the notation is array_field.index where the index is in [0, length - 1]. 在不知道数组长度的情况下就不可能引用数组的最后一个元素,因为表示法是array_field.index ,其中索引位于[0,length-1]中。 You could use the aggregation framework to create the view of the data that you want to export, save it temporarily into a collection with $out, and then mongoexport that. 您可以使用聚合框架创建要导出的数据的视图,将其临时保存到带有$ out的集合中,然后进行mongoexport。 For example, for your documents you could do 例如,对于您的文档,您可以

db.collection.aggregate([
    { "$unwind" : "$date" },
    { "$group" : { "_id" : "$_id", "date" : { "$last" : "$date" } } },
    { "$out" : "temp-for-csv" }
])

in order to get just the last date for each document and output it to the collection temp-for-csv. 为了只获取每个文档的最后日期并将其输出到temp-for-csv集合中。

You can return just the last elements in an array with the $slice projection operator, but this isn't available in aggregation and mongoexport only takes a query specification, not a projection specification, since the --fields and --fieldFile option are supposed to suffice. 您可以使用$slice投影运算符仅返回数组中的最后一个元素,但这在聚合中不可用,mongoexport仅采用查询规范,而不采用投影规范,因为假定使用--fields--fieldFile选项足够了。 Might be a good feature request to ask for using a query with a projection for mongoexport. 可能要求对mongoexport使用带有投影的查询是一个很好的功能请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM