以对象而不是数组的形式获取MongoDB结果 [英] get MongoDB results as objects instead of array
问题描述
我是MongoDB的新手,我试图以不同的方式获得结果.
I'm new to MongoDB, and I'm trying to get results in a different way.
如果我执行查询db.collection.find().toArray(),我将得到类似的东西:
if I execute the query db.collection.find().toArray() I get something like:
[
{
"_id":"34234...",
"first":"Mark",
"last":"Marker"
},
{
"_id": "34235...",
"first":"Adam",
"last":"Smith"
}
]
是否有一个api可以让您接收以下结果?
is there an api that lets you to receive the results as the following?:
{
"results" : {
"34234..." :{
"_id":"34234...",
"first":"Mark",
"last":"Marker"
},
"4235..." :{
"_id": "34235...",
"first":"Adam",
"last":"Smith"
}
}
还是我需要获取结果数组并迭代每个对象并建立响应?(我想避免单光标迭代)
Or I need to get the results array and iterate every single object and build my response? (I would like to avoid the single cursor iteration)
推荐答案
我不认为有针对此的本机API函数. cursor.toArray()
从头开始遍历光标中的每个项目,因此我不必为此担心太多.我们可以跳过 toArray()
并进行自己的迭代:
I don't believe there's a native API function for that. cursor.toArray()
goes through each item in the cursor begin with, so I wouldn't worry too much about that. We can just skip the toArray()
and do our own iteration:
var obj = {}
db.collection.find().each(function(item){
obj[item._id] = item;
});
我认为这真的不会变慢.
I don't think that would really be any slower.
这篇关于以对象而不是数组的形式获取MongoDB结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!