查询MongoDB中使用条件插入数组元素?


我们首先使用文档创建一个集合 -

>db.demo11.insertOne({"ListOfStudent":[{"StudentName":"Chris","ListOfScore":[76,67,54,89]}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f6e34d7df943a7cec4fa1")
}

以下是用 find() 方法显示集合中所有文档的查询 -

> db.demo11.find().pretty();

这将产生以下输出 -

{
   "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"),
   "ListOfStudent" : [
      {
         "StudentName" : "Chris",
         "ListOfScore" : [
            76,
            67,
            54,
            89
         ]
      }
   ]
}

以下是使用条件插入数组元素的查询 -

> db.demo11.update( {"ListOfStudent.StudentName":"Chris"}, {$push:{"ListOfStudent.$.ListOfScore":98}} );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

让我们再次检查文档 -

> db.demo11.find().pretty();

这将产生以下输出 -

{
   "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"),
   "ListOfStudent" : [
      {
         "StudentName" : "Chris",
         "ListOfScore" : [
            76,
            67,
            54,
            89,
            98
         ]
      }
   ]
}

更新于: 2020-04-01

603 次浏览

开启您的 职业

完成课程以获得认证

开始
广告
© . All rights reserved.