在Mongo Aggregation中将ObjectID转换为String [英] Convert ObjectID to String in mongo Aggregation

查看:815
本文介绍了在Mongo Aggregation中将ObjectID转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在处于这种情况下: 我有一个收藏夹X:

I'm in this scenario right now: I have a collection X:

{
  _id:ObjectId('56edbb4d5f084a51131dd4c6'),
  userRef:ObjectId('56edbb4d5f084a51131dd4c6'),
  serialNumber:'A123123',
  ...
}

我需要汇总所有文档,并按userRef + serialNumber对其进行分组,因此我正在尝试使用concat:

I need to aggregate all documents, grouping them by the userRef + serialNumber, so I'm trying to use concat like this:

$group: {
        _id: {
            '$concat': ['$userRef','-','$serialNumber']
        },
       ...

因此,基本上在MongoDB中,我需要通过ObjectId和字符串的组合来对文档进行分组.但是,似乎$ concat仅接受字符串作为参数:

So basically in my aggregation in MongoDB, I need to group documents by the concatenation of a ObjectId and a string. However, It seems that $concat only accepts strings as parameters:

uncaught exception: aggregate failed: {

    "errmsg" : "exception: $concat only supports strings, not OID",
    "code" : 16702,
    "ok" : 0
}

是否可以在聚合表达式中将ObjectId转换为String?

Is there a way to convert an ObjectId to a String within an aggregation expression?

编辑:

问题是相关的,但我的解决方案不适合我的问题. (特别是因为在聚合过程中我无法使用ObjectId.toString())

This question is related, but I the solution doesn't fit my problem. (Specially because I can't use ObjectId.toString() during the aggregation)

实际上,我在Mongo的文档中找不到任何ObjectId().toString()操作,但是我想知道在这种情况下是否可以做任何棘手的事情.

Indeed I couldn't find any ObjectId().toString() operation in Mongo's documentation, but I wonder if there's any tricky thing that can be done in this case.

推荐答案

我找不到执行所需操作的方法,因此,我创建了一个MapReduce函数,最后该函数以我自己的方式生成了密钥想(串联其他键).

I couldn't find a way to do what I wanted, so instead, I created a MapReduce function that, in the end, generated the keys the way I wanted to (concatenating other keys).

最后,它看起来像这样:

At the end, it looked something like this:

db.collection('myCollection').mapReduce(
    function() {
        emit(
            this.userRef.str + '-' + this.serialNumber , {
                count: 1,
                whateverValue1:this.value1,
                whateverValue2:this.value2,
                ...
            }
        )
    },
    function(key, values) {
       var reduce = {}
       .... my reduce function....
        return reduce
    }, {
        query: {
            ...filters_here....
        },
        out: 'name_of_output_collection'
    }
);

这篇关于在Mongo Aggregation中将ObjectID转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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