我在Mongo集合中有以下架构:
range = Schema
name: { type: String }
category = Schema
name: { type: String },
range: { type: Schema.ObjectId, ref: 'range' }
product = Schema
name: { type: String },
category: { type: Schema.ObjectId, ref: 'category' }
(为简洁起见,我省略了所有其他字段)
我需要执行的find()返回所有产品,它们是特定范围的孩子。作为过滤器,我使用范围_id。
db.product.find( { "category.range._id": ObjectID("XXXXXX") });
这是行不通的,也不是
db.product.find( { "category.range": ObjectID("XXXXXX") });
通过_id查询子子文档的正确方法是什么?
注意:_id由mongo自动生成
谢谢!
答案 0 :(得分:1)
您要起诉猫鼬的ref,因此有2个解决方案可将产品归为一类:
$lookup
:示例,假设您具有以下数据:
产品中:
{"_id":"5c951cf16726d70011f99adc","name":"p1","category":"c1Id"}
在类别中:
{"_id":"c1Id","range":"r1"}
要从其他集合类别中查询产品:
db.category.aggregate([
{$match: {range: 'r1'}},
{$lookup: {from: "product", localField: "_id", "foreignField": "category", as: "product"}}
])
您将获得:
{"_id":"c1Id","range":"r1","product":[{"_id":"5c951cf16726d70011f99adc","name":"p1","category":"c1Id"}]}
您可以直接用猫鼬表演它。
您需要通过以下方式更改架构:
category = Schema
name: { type: String },
range: { type: Schema.ObjectId, ref: 'range' }
category.virtual('products', { ref: 'product', localField: _id", "foreignField": "category", justOne: false })
const category= await category.findOne({ _id: 'r1' }).populate('products');
// category.products will contains the products.