How to merge multiple fields in a collection?

廉价感情. 提交于 2020-01-06 03:30:08

问题


Example entry:

{ "_id" : "00-01@mail.ru", " pass" : 123654, "field2" : 235689, "field3" : "cccp123654", "field4" : "lhfrjy" }

Desired result:

{ "_id" : "00-01@mail.ru", " pass" : 123654, 235689, "cccp123654", "lhfrjy" }

I want to have two final fields (_id and pass).

I have attempted the following:

db.emails.aggregate([
    { "$project": {
        "pass": { "$setUnion": [ "$field2", "$field3" ] }
    }}
])

However, this results in the following error:

2018-01-22T03:01:26.074+0000 E QUERY    [thread1] Error: command failed: {
        "ok" : 0,
        "errmsg" : "All operands of $setUnion must be arrays. One argument is of type: string",
        "code" : 17043,
        "codeName" : "Location17043"
} : aggregate failed :

_getErrorWithCode@src/mongo/shell/utils.js:25:13
    doassert@src/mongo/shell/assert.js:16:14
    assert.commandWorked@src/mongo/shell/assert.js:370:5
    DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1319:5
    @(shell):1:1

Can someone assist?


回答1:


we can convert $objectToArray and $slice after 1 element in array

> db.io.aggregate(
    [
        {$addFields : {arr : {$objectToArray : "$$ROOT"}}}, 
        {$project : { pass : {$slice : ["$arr.v", 1, 20 ] }}}
    ]
).pretty()

result

{
    "_id" : "00-01@mail.ru",
    "pass" : [
        123654,
        235689,
        "cccp123654",
        "lhfrjy"
    ]
}
> 


来源:https://stackoverflow.com/questions/48374158/how-to-merge-multiple-fields-in-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!