1

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?

  • Try `{ "$project": { "pass": [ "$field2", "$field3" ] }}` – s7vr Jan 22 '18 at 03:08
  • @Veeram This does not work, it breaks all the fields, see { "_id" : "00!foro@bk.ru", "pass" : [ null, null ] } – user9249456 Jan 22 '18 at 03:29
  • Are some fields optional ? and you just want to merge fields when they exist ? – s7vr Jan 22 '18 at 03:30
  • @Veeram Well, each document has a different amount of fields, anywhere from 1 to 15 but always _id and $pass at bare minimum. – user9249456 Jan 22 '18 at 03:31
  • Still not clear. The expected output for "pass" you've is a invalid format. What command do you need to revert ? Aggregation doesn't update collection. Please update the post. – s7vr Jan 22 '18 at 03:35
  • @Veeram How is it not clear? I want to join all data under field* columns to the pass column. – user9249456 Jan 22 '18 at 03:44

1 Answers1

0

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"
    ]
}
> 
Saravana
  • 12,647
  • 2
  • 39
  • 57