mongodb - Find the last element in an array -


i have data below:

{ "_id" : objectid("569a5328c5905e1b08113987"), "dataid" : "003f2d9c0b9b0f047df458b78a12404a", "datasensors" : [      {         "iotserial" : "7ee042ad9d01e3e53c1b05d8923ce2ec",         "datemesure" : "2016-01-16 15:51:41",         "value" : "0.47"     },  {         "iotserial" : "aaa042ad9d0aaaaaa1b05d8923ce2aa",         "datemesure" : "2016-01-16 15:51:40",         "value" : "15.66"     },     {         "iotserial" : "7ee042ad9d01e3e53c1b05d8923ce2ec",         "datemesure" : "2016-01-16 15:51:40",         "value" : "15.66"     },      {         "iotserial" : "7ee042ad9d01e3e53c1b05d8923ce2ec",         "datemesure" : "2016-01-16 15:51:42",         "value" : "10.15"     } ], "statusflag" : "poi"} 

when use

db.collection.find({dataid:"003f2d9c0b9b0f047df458b78a12404a"},{datasensors:{$elemmatch:{iotserial:"7ee042ad9d01e3e53c1b05d8923ce2ec"}}}) 

it returns first member of series,

{ "_id" : objectid("569a5328c5905e1b08113987"), "datasensors" : [      {         "iotserial" : "7ee042ad9d01e3e53c1b05d8923ce2ec",         "datemesure" : "2016-01-16 15:51:41",         "value" : "0.47"     } ]} 

but need last element "value" : "10.15"

thanks in advance

you're using find incorrectly.

second argument of find not query, projection.

use find single query condition in query , $slice: -1 in projection last element of array:

db.collection.find({   dataid:"003f2d9c0b9b0f047df458b78a12404a",   "datasensors.iotserial":"7ee042ad9d01e3e53c1b05d8923ce2ec" }, {   datasensors:{       $slice: -1   } }); 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -