【发布时间】:2017-01-29 01:36:14
【问题描述】:
我有这个猫鼬模型:
var mySubEntitySchema = new Schema({
property1: String,
property2: String
});
var myEntitySchema = new Schema({
name: String,
sub: [mySubEntitySchema]
});
export var MyEntityModel: mongoose.Model<MyEntityDocument> = mongoose.model<MyEntityDocument>("MyEntity", myEntitySchema);
现在我想获取一个特定的 MyEntityDocument,我有它的 _id,但只有与 property1 = "example" 匹配的子文档。
有什么办法吗?
我尝试了使用 Aggregate 的解决方案,但没有成功:
MyEntityModel.aggregate([
{$match: { "_id": myId, "sub.property1":"example" }},
{$unwind: "$sub"},
{$match: { "sub.property1":"example"}},
{$group: {"_id":"$_id","subs":{$push:"$sub"}}}
], (error, result) => {
console.log("Result = " + JSON.stringify(result));
}
});
但它什么也没返回。如果我不将 "_id": myId 放在第一个 $match 子句中,那么我会得到结果,但我只想要与我拥有的 _id 对应的一个结果。
有人知道我该怎么做吗?
编辑:按照要求,这是一个示例。
有了这些数据:
{
"_id": "54c12276fcb2488d300795e4",
"name": "a",
"sub": [
{
"_id": "54c12276fcb2488d300795e0",
"property1": "example",
"property2": "something"
},
{
"_id": "54c12276fcb2488d300795e1",
"property1": "notmuch",
"property2": "somethingelse"
},
{
"_id": "54c12276fcb2488d300795e2",
"property1": "notinteresting",
"property2": "something"
},
{
"_id": "54c12276fcb2488d300795e3",
"property1": "example",
"property2": "anotherthing"
}
]
},
{
"_id": "54c12277fcb2488d300795e5",
"name": "b",
"sub": [
{
"_id": "54c12276fcb2488d300795e6",
"property1": "example",
"property2": "word"
}
]
}
我想要 _id 为“54c12276fcb2488d300795e4”的实体和匹配 property1 =“example”的子文档。所以预期的结果是:
{
"_id": "54c12276fcb2488d300795e4",
"name": "a",
"sub": [
{
"_id": "54c12276fcb2488d300795e0",
"property1": "example",
"property2": "something"
},
{
"_id": "54c12276fcb2488d300795e3",
"property1": "example",
"property2": "anotherthing"
}
]
}
【问题讨论】:
-
你能在这里添加一个样本数据集和你想要的结果吗??
-
@AnanthPai 刚刚编辑以添加示例数据和预期结果。
标签: mongoose subdocument