我在javascript中使用猫鼬,但希望能得到纯MongoDB或猫鼬的答案。
假设我们在数据库中有一个如下所示的模式:
{
attr1: String,
attr2: Number,
arr: [String]
}
这种模式的对象可以在数组中包含数百个元素,但是我希望MongoDB仅返回数组中的5个最新(最后)元素。
更明确的示例:
数据库中的对象:
{
attr1: "test",
attr2: 4,
arr: [ "test1", "test2", "test3", "test4", "test5", "test6", "test7" ]
}
我想由MongoDB返回的对象:
{
attr1: "test",
attr2: 4,
arr: [ "test3", "test4", "test5", "test6", "test7" ]
}
答案 0 :(得分:1)
您可以使用$slice
投影运算符来完成此操作:
db.test.find({}, {arr: {$slice: -5}})
输出:
{ "_id" : ...,
"attr1" : "test",
"attr2" : 4,
"arr" : [ "test3", "test4", "test5", "test6", "test7" ]
}
传递负值将从数组中获取最后N个元素。