skip to Main Content

I am new to MongoDB. I have a VIEW created on a collection, I need to make a modification to this VIEW.
Say we have a collection CollectionName. It has an array field aArray. This arrays has 2 fields, arrayField1 and arrayField2. Currently, the fields are being selected from aArray as below :

$replaceRoot :
{
  newRoot: {
    $mergeObjects: [
      {
        arrayFieldNew1: '$aArray.arrayField1',
        arrayFieldNew1: '$aArray.arrayField2'
      }
    ]
  }
}

Now, a new array bArray is added to the collection. The bArray is same as aArray. The field names of bArray are same as aArray which are arrayField1 and arrayField2.I need to select arrayField1 and arrayField2 from aArray, only if bArray is not present. If bArray exists then select arrayField1 and arrayField2 from bArray.

I hope I am able to communicate my requirement.

I have tried googling this problem but didn’t get any solution.

2

Answers


  1. This can be accomplished by using $cond and $type for each field, such as:

            arrayFieldNew1: {$cond:{
                       if: {$eq:[{$type:"$bArray"},'missing']},
                       then: '$aArray.arrayField1',
                       else: '$bArray.arrayField1'
            }}
    
    Login or Signup to reply.
  2. You can use conditionals to solve this. A suitable one is $ifNull.

    See demo at https://runkit.com/embed/jatnkig9hbye

    db.collection.insertMany([
      {
        aArray: {
          arrayField1: "A"
        },
        bArray: {
          arrayField2: "B"
        }
      }
    ])
    
    const res = db.collection.aggregate([
      {
        "$project": {
          "arrayField1": {
            "$ifNull": [
              "$bArray.arrayField1", // check bArray first
              "$aArray.arrayField1"
            ]
          }
        }
      }
    ])
    
    console.log(res) // [{"arrayField1": "A"}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search