LukasMP LukasMP - 1 year ago 64
Javascript Question

Projection field in mongodb for another field

I have the follow example of Json:

{
"status": "1",
"instancia": "1",
"infoAdicionais": {
"partes": [{
"id": "123"
}]
}
}


I want some mode to put de partes array out of object, somelike this:

{
"status": "1",
"instancia": "1",
"partes": [{
"id": "123"
}]
}


find command works? I'm using mongodb 2.0, aggregate function is not available for that.

Thanks

Answer Source

It seems that from this mongodb blog post, aggregation framework is available on mongodb 2.2 including $project.

The following will :

  • $project all fields but infoAdicionals & creating a new one with $infoAdicionais.partes

In mongo 2.2 query is :

db.runCommand({
  aggregate: "device",
  pipeline: [{
    $project: {
      "status": 1,
      "instancia": 1,
      "partes": "$infoAdicionais.partes"
    }
  }]
});

In mongo 2.6+ query is :

db.device.aggregate([{
  $project: {
    "status": 1,
    "instancia": 1,
    "partes": "$infoAdicionais.partes"
  }
}])

In mongo 2.0.0, I iterate each item with a cursor, add a property & remove another :

var cursor = db.device.find();

while(cursor.hasNext()){
    var item = cursor.next();
    item.partes=item.infoAdicionais.partes;
    delete item['infoAdicionais'];
    printjsononeline(item);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download