MongoDB:比较嵌套数组并删除单个条目

时间:2018-02-21 12:37:28

标签: node.js mongodb mongoose

如果“moduleOne_data”条目的子元素“years”与数组“currentYears”不同,我想删除数组“moduleOne_data”中的每个条目。

我拥有的东西:

{
  _id : ObjectId("5a8d2f803d516722fcf94fd1"),
  name : "testName",
  appData : {
    moduleOne : {
        moduleOne_data : [ 
            {
                date : "20180221-1",
                years : [ 
                    2013, 
                    2014, 
                    2015, 
                    2016, 
                    2017
                ],
                status : "done"
            }, 
            {
                date : "20180221-2",
                years : [ 
                    2013, 
                    2014, 
                    2015, 
                    2016
                ],
                status : "done"
            }, 
            {
                date : "20180221-3",
                years : [ 
                    2013, 
                    2014, 
                    2015
                ],
                status : "done"
            }
        ],
        currentYears : {
            years : [ 
                2013, 
                2014, 
                2015, 
                2016
            ]
        }
    }
  }
}

在我的例子中,数组“moduleOne_data”中第二个条目的年份匹配“currentYears”数组的年份。所以我想删除第一个和第三个条目。

更新后我想要的是:

{
  _id : ObjectId("5a8d2f803d516722fcf94fd1"),
  name : "testName",
  appData : {
    moduleOne : {
        moduleOne_data : [ 
            {
                date : "20180221-2",
                years : [ 
                    2013, 
                    2014, 
                    2015, 
                    2016
                ],
                status : "done"
            }
        ],
        currentYears : {
            years : [ 
                2013, 
                2014, 
                2015, 
                2016
            ]
        }
    }
  }
}

编辑:到目前为止我尝试了什么:

for (j = 0; j < appData.moduleOne.moduleOne_data.length; j++) {
  db.collection.update(
    {"_id":ObjectId("5a8d2f803d516722fcf94fd1")},
    { $pull: { "appData.moduleOne.moduleOne_data" : { years: { $not: appData.moduleOne.currentYears.years } } } }
  );
}

1 个答案:

答案 0 :(得分:0)

试试这个

["Jane", "is",
"running"]