mongodb求教关于find和save问题
发布于 1 年前 作者 anple2008 1056 次浏览 最后一次编辑是 4 个月前 来自 问答

1.查找记录如下:find()多条文档集合A,然后要保存修改后的文档,只能通过 for(var i=0; i<A.length; i++){A[i].save();}吗? 2.mongos中save过程会不会判断文档数据有没被修改,没修改就直接返回?

项目中find有100多条文档,下线了会操作save过程,如果是save过程比较耗时对系统会有影响。有没其他方法可以替代。

3 回复

同问啊,我也遇到类似的问题,不过操作数组可以考虑用async来操作

可以用findByIdAndUpdate() 这样就不需要处理集合A

Model.findByIdAndUpdate(id, [update], [options], [callback])

Issues a mongodb findAndModify update command by a documents id.

show code Parameters:

id <ObjectId, HexId> an ObjectId or string that can be cast to one. [update] <Object> [options] <Object> [callback] <Function> Returns:

<Query> See:

Model.findOneAndUpdate mongodb Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes immediately if callback is passed else a Query object is returned.

Options:

new: bool - true to return the modified document rather than the original. defaults to true upsert: bool - creates the object if it doesn’t exist. defaults to false. sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update select: sets the document fields to return

1.我所知道的更新数据的基本命令就只有:update,save mongoose官方文档 2.save需要遍历集合,效率低,如果对象已存在调用update更新里面的文档。如果只是插入建议使用insert。 mongodb基本命令就是这么几个,如果你想提高效率,最直接的方法就是建议好的索引,提高遍历检索效率 mongo索引

回到顶部