[英]MongoDB with Mongoose - Find only certain child documents
MongoDB 3.0.7和Mongoose 4.3.4。
架构:
var schema = new mongoose.Schema({
confirmed: { type: Boolean, default: false },
moves: [new mongoose.Schema({
name: { type: String, default: '' },
live: { type: Boolean, default: true }
})]
});
mongoose.model('Batches', schema);
查询:
var Batch = mongoose.model('Batches');
var query = {
confirmed: true,
moves: {
$elemMatch: {
live: true
}
}
};
Batch.find(query).exec(function(err, batches){
console.log('batches: ', batches);
});
我需要返回所有已confirmed
批次,以及返回的live
批次中的所有移动。
目前,以上仅返回已confirmed
批次(这是我想要的),但是每个返回的批次中的所有 moves
(这都不是我想要的)。 因此,通过live
标志限制移动不起作用。
如何限制返回的子文档?
理想情况下,我想保留所有控制传递给find
query
返回的数据的控件,而不必在Batch
上调用更多方法。
对于支持MongoDB Server 3.2.x
Mongoose版本>=4.3.0
,可以将$filter
运算符与聚合框架一起使用,以根据指定条件限制/选择要返回的moves数组的子集。 这将返回仅包含与条件匹配的那些元素的数组,因此您将在$project
阶段中使用它来基于上面的过滤器修改moves数组。
以下示例显示了如何执行此操作:
var Batch = mongoose.model('Batches'),
pipeline = [
{
"$match": { "confirmed": true, "moves.live": true }
},
{
"$project": {
"confirmed": 1,
"moves": {
"$filter": {
"input": "$moves",
"as": "el",
"cond": { "$eq": [ "$$el.live", true ] }
}
}
}
}
];
Batch.aggregate(pipeline).exec(function(err, batches){
console.log('batches: ', batches);
});
或使用流畅的aggregate()
API管道构建器:
Batch.aggregate()
.match({
"$match": { "confirmed": true, "moves.live": true }
})
.project({
"confirmed": 1,
"moves": {
"$filter": {
"input": "$moves",
"as": "el",
"cond": { "$eq": [ "$$el.live", true ] }
}
}
})
.exec(function(err, batches){
console.log('batches: ', batches);
});
对于支持MongoDB Server >=2.6.x
Mongoose版本~3.8.8, ~3.8.22, 4.x
您可以使用$map
和$setDifference
运算符的组合来滤除错误值:
var Batch = mongoose.model('Batches'),
pipeline = [
{
"$match": { "confirmed": true, "moves.live": true }
},
{
"$project": {
"confirmed": 1,
"moves": {
"$setDifference": [
{
"$map": {
"input": "$moves",
"as": "el",
"in": {
"$cond": [
{ "$eq": [ "$$el.live", true ] },
"$$el",
false
]
}
}
},
[false]
]
}
}
}
];
Batch.aggregate(pipeline).exec(function(err, batches){
console.log('batches: ', batches);
});
您可以使用聚合框架的$unwind
方法将它们拆分为单独的文档,这里是示例代码。
Batches.aggregate(
{ $match: {'confirmed': true, 'moves.live': true}},
{$unwind: '$moves'},
{$project: {
confirmed: 1
name: '$moves.name',
live:'$moves.live'
}
}, function(err, ret){
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.