mongodb:将字段移动到新文档并更新字段和数组

时间:2016-01-29 09:56:37

标签: javascript mongodb meteor

Collection.find({ $and: [ {title: { $exists: true}}, {reference: { $exists: true }} ]}).pretty()

这给了我一些结构文件:

{
    "_id" : "EJBFtZ7EeGbBPwJaw",
    "title" : "title",
    "reference" : "8uujF9pivpGA37oQc",
    "parent" : "v7DJzq859XX4kvKPi",
    "ancestors" : [
        "v7DJzq859XX4kvKPi"
    ]
}

现在我必须改变所有文件:

  1. 将标题移至新文档
  2. parent ID更新为新文档
  3. 将新id推送到祖先(在第一个位置!)
  4. 结果应为:

    {
        "_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
                }
            );      
        }
    
    });
    
    1. 但是执行$push会附加id而不是在它之前添加。
    2. 使用if (newId) {}是正确的还是我应该将此部分放在insert的回调函数中?
    3. 如果有任何改进,请告诉我。

1 个答案:

答案 0 :(得分:1)

1)尝试$ position变量https://docs.mongodb.org/master/reference/operator/update/position/#up._S_position

2)我个人会像MongoDB插入方法一样返回创建的新_ID。

此致