Bruno SENELLART
Bruno SENELLART

Reputation: 163

How to separate a result in 2 fields

I am looking to find if a specific field is an Array or not. And return both in 2 distinct field. I am trying with a $project for now.

I would like to separate those 2 fields in a project as shown below. However I am stuck when it comes to divide the result. I am quite new on noSQL and I don't manage to have "$value.FieldId" which are array list in one field and all the "$value.FieldId" which are not array in the other field.

I want to perform an $setunion on the field "value.FieldId". But $setunion only accept array type as an entry. And my "value.FieldId" is not always of array type, it's sometimes a simple string.

Therefor I need to split the two componeent of the "value.FieldId" in 2 distincts fields. In isArray all the "value.FieldId" which are of array type and in isNotArray all the "value.FieldId" which are not of array type.

   db.getCollection('collectionA').aggregate([
   {
      $project: {
         item: 1,
         matricule : "$value.id",
         isArray: {$isArray:"$value.FieldId"},
         isNotArray: {$isArray:"$value.FieldId"},
      }
   }
] )

If you have a lead or any advice for this situation it would be really helpfull.

Upvotes: 1

Views: 47

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17925

Yes, $setUnion will only work if the given field is of type array in all documents of a collection, So please try this to make it work :

var inputArr = [7,8]
    db.CollectionA.aggregate(
       [
        {$project: {arr: {
                     $cond: { if: {  $isArray: "$arr"   }, then: { $setUnion: [ inputArr, "$arr" ] }, else: '$arr' }
                   }
               }
           }
       ]
    )

Collection :

/* 1 */
{
    "_id" : ObjectId("5df8b596400289966e77e268"),
    "arr" : [ 
        1, 
        2, 
        3
    ]
}

/* 2 */
{
    "_id" : ObjectId("5df8b5a0400289966e77e32e"),
    "arr" : [ 
        4, 
        5, 
        6
    ]
}

/* 3 */
{
    "_id" : ObjectId("5df8b5a9400289966e77e3ee"),
    "arr" : 1
}

Result :

/* 1 */
{
    "_id" : ObjectId("5df8b596400289966e77e268"),
    "arr" : [ 
        1, 
        2, 
        3, 
        7.0, 
        8.0
    ]
}

/* 2 */
{
    "_id" : ObjectId("5df8b5a0400289966e77e32e"),
    "arr" : [ 
        4, 
        5, 
        6, 
        7.0, 
        8.0
    ]
}

/* 3 */
{
    "_id" : ObjectId("5df8b5a9400289966e77e3ee"),
    "arr" : 1
}

Upvotes: 1

Related Questions