如何在数组MongoDB中获取指定的对象

时间:2018-04-16 08:36:37

标签: javascript arrays json node.js mongodb

我正在研究NodeJS和MongoDB,我有像这样的数据库JSON

{
   _id: "123"
   classroom: [
    {
      classId: "2046"
      className: "10b"
    },
    {
      classId: "2079"
      className: "12b"
    }   
  ]
},

{
   _id: "456"
   classroom: [
    {
      classId: "2069"
      className: "36b"
    },
    {
      classId: "2011"
      className: "36c"
    }   
  ]
}

我想删除课堂

  

_id:" 123"并有classId:" 2046"

,所以在删除过程之后,我会有像这样的JSON

   {
       _id: "123"
       classroom: [
        {
          classId: "2079"
          className: "12b"
        }   
      ]
    },

    {
       _id: "456"
       classroom: [
        {
          classId: "2069"
          className: "36b"
        },
        {
          classId: "2011"
          className: "36c"
        }   
      ]
    }

所以请帮助我这样做,非常欢迎任何建议,谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用此查询执行此操作:

db.collection.update({
    _id: '123'
}, {
    $pull: {
        classroom: {
            classId: '2046'
        }
    }
});