1

I have the data like 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 i use

db.collection.find({dataId:"003f2d9c0b9b0f047df458b78a12404a"},{dataSensors:{$elemMatch:{IoTserial:"7ee042ad9d01e3e53c1b05d8923ce2ec"}}})

It returns the first member of the series,

{
"_id" : ObjectId("569a5328c5905e1b08113987"),
"dataSensors" : [ 
    {
        "IoTserial" : "7ee042ad9d01e3e53c1b05d8923ce2ec",
        "dateMesure" : "2016-01-16 15:51:41",
        "value" : "0.47"
    }
]}

but I need the last element with "value" : "10.15"

Thanks in advance

Dusan Krstic
  • 663
  • 10
  • 17
  • Possible duplicate of [using $slice operator to get last element of array in mongodb](http://stackoverflow.com/questions/21952005/using-slice-operator-to-get-last-element-of-array-in-mongodb) – Idos Jan 16 '16 at 16:30

1 Answers1

2

You're using find incorrectly.

Second argument of find is not a query, but a projection.

Use find with single query condition in query and $slice: -1 in projection to get the last element of the array:

db.collection.find({
  dataId:"003f2d9c0b9b0f047df458b78a12404a",
  "dataSensors.IoTserial":"7ee042ad9d01e3e53c1b05d8923ce2ec"
},
{
  dataSensors:{  
    $slice: -1
  }
});
krl
  • 5,087
  • 4
  • 36
  • 53