1

I have a mongodb schema where documents are as per below structure ,

{"_id":"5e4aaadefrbff2150c42ed5b",
"data":[{"time":"15:24:31","amount":"34"},{"time":"15:24:33","amount":"38"},,{"time":"15:24:35","amount":"95"}],
"code":"S04",
"rollnumber":4,
"intime":"2020-02-16T12:24:21.921Z"}

And in my node.js code i am fetching data in this way to find the last array value,

mycollection.find({ code: "S04", rollnumber: 4 }, { "_id": 0, code: 0, rollnumber: 0, intime: 0, data: { $slice: -1 } }, (err, result) => {
            if (err) { console.log('err', err); }
            console.log(result)
            res.json(result);
        });

The problem is, i want only array result hence put all other keys:0 . It doesn't work when i put only data:1, data: { $slice: -1 }

It works when in put data:1 without slice operator. In production the list is going to be a big so i can not put all the keys with :0 in query. Please suggest how to put $slice with :1 to display only filtered array.

1 Answer 1

2

It doesn't work like that, if you include _id it should work, but it you just need data then alternatively you can try this :

db.collection.aggregate([
              {$match : {code: "S04", rollnumber: 4}},
              {$project : { _id :0, data : {$slice : [ "$data", -1 ]}}}
])

Test : MongoDB-Playground

Sign up to request clarification or add additional context in comments.

Comments

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.