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

1

1 Answer 1

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
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! This is it what I was looking for. Thanks alot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.