简体   繁体   中英

Update mongodb subdocuments with different values using mongoose

I am using mongodb in my application as backend database. And trying to update the sub-documents of a document with different values using mongoose.

Below is the sample schema for the document:

'use strict';
 const mongoose = require('mongoose');

 const activitiesSchema = new mongoose.Schema({
   activityId : {
     type: String
   },
   name: {
     type: String,
   },
   points : {
     type : String
   }
 });

 const sampleSchema = new mongoose.Schema(
 {
   userId: {
     type: String,
     require: true,
   },
   userName: {
     type : String,
   },
   activities: {
     type: [activitiesSchema],
   },
   createdTime: {
     type : Date,
     default: Date.now,
   }
 },
);
const Sample = mongoose.model('Samples', sampleSchema, 'Samples');
module.exports = Sample;

I want to update the name to run if the activityId is 001 and, if the activity id is 002 I want the name to be update to walk .

Is this possible to do in single database find and update operation?

Thank you,
KK

You can use pipelined form of update function, like this:

db.collection.update({},
[
  {
    "$set": {
      "activites": {
        $map: {
          input: "$activites",
          as: "item",
          in: {
            activityId: "$$item.activityId",
            points: "$$item.points",
            name: {
              $switch: {
                branches: [
                  {
                    case: {
                      $eq: [
                        "$$item.activityId",
                        "001"
                      ]
                    },
                    then: "run"
                  },
                  {
                    case: {
                      $eq: [
                        "$$item.activityId",
                        "002"
                      ]
                    },
                    then: "walk"
                  },
                  
                ],
                default: "$$item.name"
              }
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Playground link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM