How to find into mongodb to the last item of an array?

后端 未结 5 1649
无人及你
无人及你 2020-12-29 16:31

I want to find documents where last elements in an array equals to some value. Array elements may be accessed by specific array position:

// i.e. comments[0]         


        
5条回答
  •  盖世英雄少女心
    2020-12-29 17:02

    I am not sure why my answer above is deleted. I am reposting it. I am pretty sure without changing the schema, you should be able to do it this way.

    db.example.find({ "comments:{$slice:-1}.by" : "Abe" } 
    

    // ... or

    db.example.find({ "comments.by" : "Abe" }
    

    This by default takes the last element in the array.

提交回复
热议问题