MongoDB:动态ID数组跨集合$in查询无结果的解决方法
问题解决:适配MongoDB $in查询的数组结构调整与代码重构
问题根源
你的array_of_docs_bought最终是二维数组,因为doc[i].list_of_docs_bought本身就是一个ID数组,直接push会把整个数组作为元素存入,导致结构类似[[id1, id2], [id3, id4]],而MongoDB的$in运算符仅支持一维ID数组作为参数。
方案一:扁平化数组(快速修复)
将二维数组转换为一维数组,有两种简洁写法:
- 用扩展运算符修改循环:
let collection = database.collection('login') let doc = await collection.find({ email: req.session.username }).toArray() let array_of_docs_bought = [] for (var i = 0; i < doc.length; i++) { // 展开list_of_docs_bought的元素,逐个加入数组 array_of_docs_bought.push(...doc[i].list_of_docs_bought) } let documents = await database.collection('documents').find({ "id": { $in: array_of_docs_bought } }).toArray()
- 用
flatMap简化数组处理:
let collection = database.collection('login') let doc = await collection.find({ email: req.session.username }).toArray() // 直接提取并扁平化所有list_of_docs_bought数组 let array_of_docs_bought = doc.flatMap(item => item.list_of_docs_bought) let documents = await database.collection('documents').find({ "id": { $in: array_of_docs_bought } }).toArray()
方案二:用MongoDB聚合查询重构(更高效)
避免客户端处理数组,直接通过数据库聚合完成关联查询,减少两次IO开销:
let documents = await database.collection('login').aggregate([ // 匹配目标用户的login文档 { $match: { email: req.session.username } }, // 展开list_of_docs_bought数组,每个ID单独成为一条记录 { $unwind: "$list_of_docs_bought" }, // 关联documents集合,匹配ID { $lookup: { from: "documents", localField: "list_of_docs_bought", foreignField: "id", as: "matched_docs" } }, // 展开关联结果数组 { $unwind: "$matched_docs" }, // 将关联的文档作为结果返回 { $replaceRoot: { newRoot: "$matched_docs" } } ]).toArray()
这个方案直接在数据库层面完成关联,无需客户端处理数组转换,性能更优,尤其适合数据量较大的场景。
内容的提问来源于stack exchange,提问作者devofto
相关产品推荐
相关产品推荐

