Convert ObjectID to String in mongo Aggregation

后端 未结 5 1190
我在风中等你
我在风中等你 2021-02-05 12:15

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

{
  _id:ObjectId(\'56edbb4d5f084a51131dd4c6\'),
  userRef:ObjectId(\'56edbb4d5f084a51131dd4c6\'),
  seria         


        
相关标签:
5条回答
  • 2021-02-05 12:36

    You can simply use $toString to apply $concat in aggregation on ObjectIDs in the following way -

    $group: {
        '_id': {
            '$concat': [
                { '$toString' : '$userRef' },
                '-',
                { '$toString' : '$serialNumber'}
            ]
        },
    }
    
    0 讨论(0)
  • 2021-02-05 12:39

    I think you may try to resolve it by using an Array which contains both fields:

    {$project:{newkey:['$userRef','$serialNumber']},{$match:{newkey:{$in:filterArray}}}}
    

    this may match the data with both fields to the filter. Please notice that the data in the newkey array should have the same data type with the filterArray elements.

    0 讨论(0)
  • 2021-02-05 12:46

    Now you can try with $toString aggregation which simply converts ObjectId to string

    db.collection.aggregate([
        { "$addFields": {
            "userRef": { "$toString": "$userRef" }
        }},
        { "$group": {
          "_id": { "$concat": ["$userRef", "-", "$serialNumber"] }
        }}
    ])
    

    You can check the output here

    0 讨论(0)
  • 2021-02-05 12:50

    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'
        }
    );
    
    0 讨论(0)
  • 2021-02-05 12:51

    You can use $substr https://docs.mongodb.com/manual/reference/operator/aggregation/substr/#exp._S_substr to cast any object to string before $concat.

    This is a sample of code that's working for me.

    group_id_i['_id'] = {
        '$concat' => [
            { '$substr' => [ {'$year' => '$t'}, 0, -1] }, '-',
            { '$substr' => [ {'$month' => '$t'}, 0, -1] }, '-',
            { '$substr' => [ {'$dayOfMonth' => '$t'}, 0, -1] }
        ]
    } 
    

    Where t is DateTime field, this aggregation returns data like so.

    {
        "_id" => "28-9-2016",
        "i" => 2
    }
    
    0 讨论(0)
提交回复
热议问题