Dusan Krstic
Dusan Krstic

Reputation: 705

Find the last element in an array

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

Upvotes: 1

Views: 3580

Answers (1)

krl
krl

Reputation: 5296

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
  }
});

Upvotes: 2

Related Questions