想象一下,您有以下猫鼬模式:
mongoose.model('Team', mongoose.Schema(
{
players : [{
trikots : [{
isNew : Boolean,
color : String
}]
}]
})我想查询我的数据,以获得所有匹配的团队
我从使用$elemMatch作为子文档开始,但是他们的播放器仍然是假的。我必须使用聚合()吗?又是如何做到的?
发布于 2015-05-07 21:05:21
是的,这在聚合框架中是可以实现的。聚合管道将由一个$match操作符组成,该操作符将成为初始阶段。这将根据指定的标准筛选集合中的文档。接下来的管道步骤将是两个数组( players和嵌套players.trikots )上的两个players.trikots操作符。在$uniwnd之后,您将需要另一个$match,然后将解构的数组文档过滤到所需的条件,这将成为您的最终解决方案。
让我们通过向mongo中的team集合插入具有上述模式的几个文档来演示这一点:
db.team.insert([
{
"players" : [
{
"trikots" : [
{
"isNew" : true,
"color" : "red"
},
{
"isNew" : true,
"color" : "blue"
}
]
},
{
"trikots" : [
{
"isNew" : false,
"color" : "red"
},
{
"isNew" : true,
"color" : "green"
}
]
}
]
},
{
"players" : [
{
"trikots" : [
{
"isNew" : false,
"color" : "red"
},
{
"isNew" : false,
"color" : "blue"
}
]
}
]
}
])然后,可以按以下方式实现上述聚合管道:
var pipeline = [
{
"$match": {
"players.trikots.isNew": true,
"players.trikots.color": "red"
}
},
{
"$unwind": "$players"
},
{
"$unwind": "$players.trikots"
},
{
"$match": {
"players.trikots.isNew": true,
"players.trikots.color": "red"
}
}
];
db.team.aggregate(pipeline);输出:
/* 1 */
{
"result" : [
{
"_id" : ObjectId("554bce9a2ba32ccf7f139bae"),
"players" : {
"trikots" : {
"isNew" : true,
"color" : "red"
}
}
}
],
"ok" : 1
}你的猫鼬聚集会是相似的:
Team.aggregate(pipeline).exec(callback);或者使用猫鼬聚合管道生成器进行一次流利的呼叫:
Team.aggregate()
.match({"players.trikots.isNew": true,"players.trikots.color": "red"})
.unwind("players")
.unwind("players.trikots")
.match({"players.trikots.isNew": true,"players.trikots.color": "red"})
.exec(callback);https://stackoverflow.com/questions/30111186
复制相似问题