如何选择在mongodb排序结果中显示哪些字段?
在mongodb中,我想根据属性X在集合中查找一些文档,按属性Y排序,然后只显示属性Z,例如如何选择在mongodb排序结果中显示哪些字段?,mongodb,Mongodb,在mongodb中,我想根据属性X在集合中查找一些文档,按属性Y排序,然后只显示属性Z,例如 db.getCollection('something') .find({X: "blah"}) .sort({Y: -1}) .find({}, {Z: 1}) 但是mongo抱怨说 Error: TypeError: db.getCollection(...).find(...).sort(...).find is not a function 我如何才能做到这一点?可能是因为同时使用两个查找函
db.getCollection('something')
.find({X: "blah"})
.sort({Y: -1})
.find({}, {Z: 1})
但是mongo抱怨说
Error: TypeError: db.getCollection(...).find(...).sort(...).find is not a function
我如何才能做到这一点?可能是因为同时使用两个查找函数有问题 如果你只想在结果中显示z,那么就这样做
db.getCollection('something')
.find({X: "blah"},'-_id z')
.sort({Y: -1});
可能问题在于同时使用两个查找函数 如果你只想在结果中显示z,那么就这样做
db.getCollection('something')
.find({X: "blah"},'-_id z')
.sort({Y: -1});
你要找的是投影。全部细节 例如,在您的情况下,它应该类似于:
db.getCollection('something')
.find({ X: "blah" }, { Z: 1 }).
.sort({ Y: -1 })
但是如果你想找更高级的东西,你也可以使用。比如:
db.getCollection('something').aggregate([
{ $match: { X: "blah" }},
{ $sort: { Y: -1 }},
{ $project: { Z: 1 }}
])
你要找的是投影。全部细节 例如,在您的情况下,它应该类似于:
db.getCollection('something')
.find({ X: "blah" }, { Z: 1 }).
.sort({ Y: -1 })
但是如果你想找更高级的东西,你也可以使用。比如:
db.getCollection('something').aggregate([
{ $match: { X: "blah" }},
{ $sort: { Y: -1 }},
{ $project: { Z: 1 }}
])
事实上,你显然不能做两个发现——那么我能做什么呢?我可以尝试map,但是我不知道我必须编写的函数的语法,特别是我不知道如何从函数中访问带有空格的属性,例如functiond{return d.some Own property;}只返回该字符串。使用second find可以做什么?你想在输出上只显示Z吗?显然,你不能做两个查找-那么我能做什么呢?我可以尝试map,但是我不知道我必须编写的函数的语法,特别是我不知道如何从函数中访问带有空格的属性,例如functiond{return d.some Own property;}只返回该字符串。使用second find可以做什么?是否只在输出db.getCollection'something'上显示Z。查找{X:blah},{Z:1}。排序{Y:-1};尝试db.getCollection'something'。查找{X:blah},{Z:1}。排序{Y:-1};