【发布时间】: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