【问题标题】:Find all objects in array that match IDs of other array - mongoDB查找数组中与其他数组的 ID 匹配的所有对象 - mongoDB
【发布时间】:2021-05-19 02:10:54
【问题描述】:

我从昨天开始一直在寻找解决方案,但找不到。我尝试了不同的方法,如$elemMatch、聚合等,但没有任何效果。要么我得到所有对象,要么只得到第一个,但绝不只得到那些具有匹配 ID 的对象。

我试图实现的目标:获取具有多个 ID 之一的数组的所有对象。

第一个参数是用户 ID,例如 60a3f7d0f988f1e57212a81e。此集合中的每个 Document 的用户 ID 都是唯一的。

第二个参数是一个类似['609d1cfe0806daba1b0502bf', '609d1bba887035b9cd4292aa']的数组,由不同的ID组成,与数组words的对象匹配。

我的方法只获取第一个对象,甚至不能使用 ID 数组(wordID)作为参数。

Words.prototype.getSpecificPersonalWords = async function(userID, wordIDs) {
const words = await personalWords.aggregate([
        {$match: 
            {"user_id": userID}
        },
        {$unwind: 
            {"path": "$words"}
        },
        {$match: 
            {"words.word_id": { $in: ['609d1cfe0806daba1b0502bf', '609d1bba887035b9cd4292aa'] } }
        }
    ])

return words
}

我要查询的文档:

{
    "_id": {
        "$oid": "60a3f7d0f988f1e57212a81e"
    },
    "user_id": "609d22188ea8aebac56f9dc3",
    "__v": {
        "$numberInt": "0"
    },
    "words": [{
        "word_id": "609d1bba887035b9cd4292aa",
        "last_practiced": "2021-05-15 16:00:00",
        "strength": {
            "$numberInt": "1"
        }
    }, {
        "word_id": "609d1c35861d99b9effc0027",
        "last_practiced": "2021-05-15 16:00:00",
        "strength": {
            "$numberInt": "1"
        }
    }, {
        "word_id": "609d1dcbc99e8dba538208d7",
        "last_practiced": "2021-05-15 16:00:00",
        "strength": {
            "$numberInt": "1"
        }
    }]
}

该文档的架构

{
    user_id: {
        type: String,
        unique: true
    },
    words: Array
});

我希望有人可以帮助我解决这个问题。提前致谢。

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:
    • $match user_idword_id 条件
    • $filter 迭代 words 的循环并匹配 id 数组中的条件 id word_id
    const words = await personalWords.aggregate([
      {
        $match: {
          "user_id": "609d22188ea8aebac56f9dc3",
          "words.word_id": {
            $in: ["609d1cfe0806daba1b0502bf", "609d1bba887035b9cd4292aa"]
          }
        }
      },
      {
        $addFields: {
          words: {
            $filter: {
              input: "$words",
              cond: {
                $in: [
                  "$$this.word_id",
                  ["609d1cfe0806daba1b0502bf", "609d1bba887035b9cd4292aa"]
                ]
              }
            }
          }
        }
      }
    ])
    

    Playground

    【讨论】:

    • 感谢您的回答!我仍然只得到一个对象。我需要获取与参数 wordIDs 的 ID 匹配的 words 数组的每个对象。
    • 你能检查你的数据吗,只有一个匹配的对象..所以它只返回一个对象..
    • 我的错,没有调整参数中的ID。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2013-09-16
    • 1970-01-01
    相关资源
    最近更新 更多