How to access elements of a mongodb array

I have a mongodb Document as below

{
    "_id" : ObjectId("213122423423423"),
    "eventDateTimes" : 
     [ 
        ISODate("2015-05-26T12:18:15.000Z"), 
        ISODate("2015-05-26T12:18:14.000Z"), 
        ISODate("2015-05-26T12:00:37.000Z"), 
        ISODate("2015-05-26T12:00:36.000Z")

     ],
    "parseFlags" : 
    [ 
        false, 
        "True", 
        false, 
        false
    ],

    "eventMessages" : [ 
        "Erro1 ", 
        "Error2", 
        "Error3", 
        "Error4"       
    ]    
    }
}

      

I need to get eventMessages based on the parseFlags array.

I need to get the index of the items in the parseFlags array where the value is "false" and then get the mapping of event messages to those indexes.

The result should be a document with the following parameters, where parseFlag is false:

{
  id,
  EventDateTimes:[date1,date3,date4],
  ParseFlags :[false,false,false]
  eventMessages :[Error1,Error3,Error4]
}

      

Could you please let me know how to get this result? I am using mongodb 3.2.

+3


source to share


1 answer


Mongodb 3.4 introduces a new zip array operator that groups array elements based on index

db.collectionName.aggregate({
  $project: { 
    transposed: {  
      $zip: {inputs: ["$eventDateTimes", "$parseFlags", "$eventMessages"]
    }
  }
},

  {$unwind: '$transposed'},
  {$project: {eventDateTime: {$arrayElemAt: ['$tranposed',0]}, parseFlag: 
  {$arrayElemAt: ['$transposed', 1]}}}
{$match: {parseFlag: false}}

)

      

For mongo 3.2, there is no direct way to handle the expected request. You can use mapReduce with custom code instead



db.collection.mapReduce(function(){
   var transposed = [];
   for(var i=0;i<this.eventDateTimes.length;i++){
       if(this.parseFlags[i]===false){
     transposed.push({eventDateTime: this.eventDateTimes[i], parseFlag: this.parseFlags[i]});
 }
   }
   emit(this._id, transposed);
}, function(key, values){
   return [].concat.apply([], values);
}, {out: {inline:1}})

      

PS: I didn't really complete the request, but the above should give you an idea of ​​how to do this.

+2


source







All Articles