我有这个猫鼬模型:
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,但只有subDocuments匹配property1 =&#34;示例&#34;。
有没有办法做到这一点?
我尝试使用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));
}
});
但它什么也没有回报。如果我没有在第一个$ match子句中放置&#34; _id&#34;:myId,那么我会得到结果,但我只想要一个与我所拥有的_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&#34; 54c12276fcb2488d300795e4&#34;和匹配property1 =&#34的子磁盘;示例&#34;。所以预期的结果是:
{
"_id": "54c12276fcb2488d300795e4",
"name": "a",
"sub": [
{
"_id": "54c12276fcb2488d300795e0",
"property1": "example",
"property2": "something"
},
{
"_id": "54c12276fcb2488d300795e3",
"property1": "example",
"property2": "anotherthing"
}
]
}
答案 0 :(得分:0)
您可以使用findOne
来检索您想要的内容。
MyEntityModel.findOne({_id : myId , "sub.property1" :"example"},{'sub.$' : 1},function(err,result){
if(!err)
{
if(result)
{
//result is the document you were searching for
}
}
});
{'sub。$':1}将只返回匹配的元素。
浏览mongoose query documentation以便更好地理解。
答案 1 :(得分:0)
您的查询似乎正常工作并且正如预期的那样得到结果,但聚合函数的语法不正确。请参阅this链接,了解如何使用mongoose编写聚合查询。您不应该像在mongodb console
中那样传递数组。只需传递逗号分隔的查询,如下面的查询所示。
MyEntityModel.aggregate(
{$match: { "_id": myId, "sub.property1":"example" }},
{$unwind: "$sub"},
{$match: { "sub.property1":"example"}},
{$group: {"_id":"$_id","name": {"$first": "$name"}, "subs":{$push:"$sub"}}}
, (error, result) => {
console.log("Result = " + JSON.stringify(result));
}
});