首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mongodb的整形结果

mongodb的整形结果
EN

Stack Overflow用户
提问于 2014-07-03 08:54:39
回答 1查看 381关注 0票数 0

在我的node.js应用程序中,我对猫鼬驱动程序使用mongodb。如何重塑Modell.find()操作的结果?如果我有这样的文档和示例:

代码语言:javascript
复制
{
   _id:   ObjectId(...),
   score: 14,
   time:  123
}

在我的查找操作中,我想在.find()的结果上添加一个索引(计数器),并重命名_id字段。这个是可能的吗?

如果想让我的文档流看起来像这样:

代码语言:javascript
复制
[{
   index:   0
   player:  ObjectId // _id field renamed to player
   score:   14,
   time:    123
},
{
   index:   1
   player:  ObjectId // _id field renamed to player
   score:   6,
   time:    321
},
...
{
   index:   N
   player:  ObjectId // _id field renamed to player
   score:   1,
   time:    456
}
]

我试过

代码语言:javascript
复制
Modell.find({}, {player: '$_id', score: 1, time: 1})
      .exec(function(err, players) {
         ...
});

但是,在生成的文档流中,_id字段没有被重命名。这个是可能的吗?以及如何在文档流中创建文档计数器。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-03 09:05:48

.find()方法不会进行这种重命名。为此,您需要聚合框架和$project操作符。

不过,文档上的索引号完全是另一回事,尽管我不明白为什么需要这样做,因为这些“索引”值已经可以访问“数组”,但是在从服务器检索“数组”之后,您将更改结果“。

代码语言:javascript
复制
Model.aggregate(
    [
        { "$project": {
            "_id": 0,
            "player": "$_id",
            "score": 1,
            "time": 1,
        }},
    ],
    function(err,results) {
        if (err) throw err;

        results = results.map(function(x,index) { x.index = index; return x; });
        console.log(results);
    }
);

实际上,如果您只想返回整个结果,您可以使用map完成整个工作:

代码语言:javascript
复制
Model.find({},function(err,result) {
    if (err) throw err;

    results = results.map(function(x,index) { 
        x.index = index;
        x.player = x._id;
        delete x._id;
        return x; 
    });

    console.log(results);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24549212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档