【问题标题】:Using MongoDB .findOne() function with nested document value使用带有嵌套文档值的 MongoDB .findOne() 函数
【发布时间】:2021-05-29 06:13:55
【问题描述】:

假设我的 MongoDB 集合中有这个文档,锻炼:

{
  _id: ObjectId("60383b491e2a11272c845749") <--- Workout ID
  user: ObjectId("5fc7d6b9bbd9473a24d3ab3e") <--- User ID
  exercises: [
    {
      _id: ObjectId("...") <--- Exercise ID
      exerciseName: "Bench Press",
      sets: [
        {
          _id: ObjectId("...") <--- Set ID
        },
        {
          _id: ObjectId("...") <--- Set ID
        }
      ]
    }
  ]
}

Workout 对象可以在练习数组中包含多个锻炼对象,并且每个锻炼对象可以在 sets 数组中包含多个集合对象。我正在尝试为某个集合实现删除功能。我需要检索存储我要删除的集合的锻炼。我可以访问用户的 ID(存储在上下文中)、锻炼 ID 和要删除的集合 ID 作为 .findOne() 的参数功能。但是,我不确定是否可以遍历锻炼对象中不同级别的数组和对象。这是我尝试过的:

const user = checkAuth(context) // Gets logged in user details (id, username)
const exerciseID, setID // Both of these are passed in already and are set to the appropriate values

const workoutLog = Workout.findOne({
  user: user.id,
  exercises: { _id: exerciseID }
});

这将返回一个空数组,但我期望包含我要删除的集合的整个 Workout 对象。我想从这个函数的参数中省略executiveID,只使用setID,但我不确定如何遍历对象数组来访问它的值。这是可能的还是我应该以另一种方式去做?谢谢。

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    您可以一步执行查找和更新。试试这个:

    db.Workout.updateOne(
        {
            "user": ObjectId("5fc7d6b9bbd9473a24d3ab3e"),
        },
        {
            $pull: {
                "exercises.$[exercise].sets": {
                    "_id": ObjectId("6039709fe0c7d52970d3fa30") // <--- Set ID
                }
            }
        },
        {
            arrayFilters: [
                {
                    "exercise._id" : ObjectId("6039709fe0c7d52970d3fa2e") // <--- Exercise ID
                }
            ]
        }
    );
    

    【讨论】:

      【解决方案2】:

      当匹配一个数组时,如果你这样指定查询:

      { exercises: { _id: exerciseID } }
      

      MongoDB 尝试执行exact match on the document。因此,在这种情况下,MongoDB 只会匹配 exercises 数组中的文档,其格式与 { _id: ObjectId("...") } 完全相同。因为exercises 中的文档还有其他字段,所以这永远不会产生匹配,即使_ids 相同。

      你想要做的是query a field of the documents in the array。完整的查询文档将如下所示:

      {
        user: user.id,
        "exercises._id": exerciseID
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-06
        • 1970-01-01
        • 1970-01-01
        • 2018-03-01
        • 1970-01-01
        • 2021-11-12
        • 1970-01-01
        • 2016-11-23
        • 1970-01-01
        相关资源
        最近更新 更多