Collection.find({ $and: [ {title: { $exists: true}}, {reference: { $exists: true }} ]}).pretty()
这给了我一些结构文件:
{
"_id" : "EJBFtZ7EeGbBPwJaw",
"title" : "title",
"reference" : "8uujF9pivpGA37oQc",
"parent" : "v7DJzq859XX4kvKPi",
"ancestors" : [
"v7DJzq859XX4kvKPi"
]
}
现在我必须改变所有文件:
parent
ID更新为新文档结果应为:
{
"_id" : "gzRn4nDKfeewb8EYE", // new document
"title" : "title", // moved title
"parent" : "v7DJzq859XX4kvKPi",
"ancestors" : [
"v7DJzq859XX4kvKPi"
]
},
{
"_id" : "EJBFtZ7EeGbBPwJaw", // removed title
"reference" : "8uujF9pivpGA37oQc",
"parent" : "gzRn4nDKfeewb8EYE", // update parent id to new id
"ancestors" : [
"gzRn4nDKfeewb8EYE", // add new id at first pos
"v7DJzq859XX4kvKPi"
]
}
所以我在想的是这样的:
Collection.find({ $and: [ {title: { $exists: true}}, {reference: { $exists: true }} ]}).forEach(function(doc) {
// get data from source
var id = doc.id;
var title = doc.title;
var parent = doc.parent;
// insert new document
var newId = Collection.insert({
title: title,
parent: parent,
ancestors: [parent]
});
// update source document
if (newId) {
Collection.update(
{ _id: id },
{
$set: { parent: newId }, // update parent id
$push: { ancestors: newId } // update ancestors array
$unset: { title: '' } // remove title
}
);
}
});
$push
会附加id而不是在它之前添加。if (newId) {}
是正确的还是我应该将此部分放在insert
的回调函数中?如果有任何改进,请告诉我。
答案 0 :(得分:1)
1)尝试$ position变量https://docs.mongodb.org/master/reference/operator/update/position/#up._S_position
2)我个人会像MongoDB插入方法一样返回创建的新_ID。
此致