mongodb 使用Mongoose遍历嵌套数组

jgwigjjp  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(199)

我试图在“ss_characteristics”数组中将键“ssfollow_sinusitis”的每个示例重命名为“sinusitis”,同时仍然保留值。
我试图使用mongoose实现这一点,但没有运气,因为似乎$rename运算符不支持在MongoDB中遍历嵌套数组。
下面是我正在查询的表的示例,以及我尝试的方法的示例,该方法不起作用:

await Form.updateMany(
  { 'ss_characteristics.$.ssfollow_sinusitis': { $exists: true } },
  { $rename: { 'ss_characteristics.$.ssfollow_sinusitis': 'ss_characteristics.$.sinusitis' } }
);
const all_forms = await Form.find({})

// console.log(all_forms) will give the below.
[
  {
    _id: new ObjectId("6413adfdea76122e6fcdefc6"),
    general_details: {
      name: 'YEYO Rae',
    },
    ss_characteristics: [
      {
        sinusitis: 'No',
        _id: new ObjectId("6450fb3d4155fbd24cb69a73")
      },
      {
        sinusitis: 'No',
        _id: new ObjectId("6450fba24155fbd24cb69ab0")
      }
    ]
  },
  {
    _id: new ObjectId("6413adfdea76122e6fcdefc6"),
    general_details: {
      name: 'OSLAVI Hig',
    },
    ss_characteristics: [
      {
        ssfollow_sinusitis: 'No',
        _id: new ObjectId("6450fb3d4155fbd24cb69a73")
      },
      {
        ssfollow_sinusitis: 'No',
        _id: new ObjectId("6450fba24155fbd24cb69ab0")
      }
    ]
  }
]
vu8f3i0k

vu8f3i0k1#

  • “ Mongoose ”:“^7.2.1”,* $rename无法重命名数组中文档的字段。可以使用Updates with Aggregation Pipeline
  • $set阶段:$setss_characteristics文档,其中新文档从其自身Map。Map逻辑为:为每个文档创建一个sinusitis字段,并将其与当前文档($$this)合并($mergeObjects)。
  • $unset阶段:删除ss_characteristics数组中每个文档的过时字段ssfollow_sinusitis
import mongoose from "mongoose";
import util from 'util';
import { config } from '../../config';

mongoose.set('debug', true);

const modelSchema = new mongoose.Schema({
  ss_characteristics: Array
});
const Model = mongoose.model('model', modelSchema);

(async function main() {
  try {
    await mongoose.connect(config.MONGODB_URI);

    // seed
    await Model.create([
      {
        ss_characteristics: [
          { sinusitis: 'No', id: new mongoose.Types.ObjectId() },
          { sinusitis: 'No', id: new mongoose.Types.ObjectId() }
        ]
      },
      {
        ss_characteristics: [
          { ssfollow_sinusitis: 'No', 'test field': 'a', id: new mongoose.Types.ObjectId() },
          { ssfollow_sinusitis: 'No', 'test field': 'b', id: new mongoose.Types.ObjectId() }
        ]
      },
      {
        ss_characteristics: [
          { ssfollow_sinusitis: 'Yes', id: new mongoose.Types.ObjectId() },
          { ssfollow_sinusitis: 'Yes', id: new mongoose.Types.ObjectId() }
        ]
      }
    ])

    // test
    const updateResult = await Model.updateMany({
      'ss_characteristics': { $elemMatch: { ssfollow_sinusitis: { $exists: true } } }
    }, [
      {
        $set: {
          ss_characteristics: {
            $map: {
              input: '$ss_characteristics',
              in: {
                $mergeObjects: [
                  '$$this',
                  {
                    sinusitis: '$$this.ssfollow_sinusitis',
                    test_field: '$$this.test field'
                  }
                ],
              }
            }
          }
        },
      },
      {
        $unset: ["ss_characteristics.ssfollow_sinusitis", 'ss_characteristics.test field']
      }
    ])
    console.log('updateResult: ', util.inspect(updateResult, false, null))

    const updateDocs = await Model.find()

    console.log('updateDocs: ', util.inspect(updateDocs, false, null))

  } catch (error) {
    console.error(error);
  } finally {
    await Promise.all(['models'].map(c => mongoose.connection.dropCollection(c)))
    await mongoose.connection.close()
  }
})();

结果:

updateResult:  {
  acknowledged: true,
  modifiedCount: 2,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 2
}
Mongoose: models.find({}, {})
updateDocs:  [
  {
    _id: new ObjectId("64774aa39b761d94ed079927"),
    ss_characteristics: [
      {
        id: new ObjectId("64774aa39b761d94ed079923"),
        sinusitis: 'Yes'
      },
      {
        id: new ObjectId("64774aa39b761d94ed079924"),
        sinusitis: 'Yes'
      }
    ],
    __v: 0
  },
  {
    _id: new ObjectId("64774aa39b761d94ed079926"),
    ss_characteristics: [
      {
        id: new ObjectId("64774aa39b761d94ed079921"),
        sinusitis: 'No',
        test_field: 'a'
      },
      {
        id: new ObjectId("64774aa39b761d94ed079922"),
        sinusitis: 'No',
        test_field: 'b'
      }
    ],
    __v: 0
  },
  {
    _id: new ObjectId("64774aa39b761d94ed079925"),
    ss_characteristics: [
      { sinusitis: 'No', id: new ObjectId("64774aa39b761d94ed07991f") },
      { sinusitis: 'No', id: new ObjectId("64774aa39b761d94ed079920") }
    ],
    __v: 0
  }
]

相关问题