Mongodb 检索数组大小之和大于给定值的文档
我有一个猫鼬模式,定义如下:Mongodb 检索数组大小之和大于给定值的文档,mongodb,mongoose,mongodb-query,aggregation-framework,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我有一个猫鼬模式,定义如下: const hackathonSchema = new mongoose.Schema({ hackathonId: {type: Number, required: true}, uuid: {type: String, required: true}, data: {type: Object, required: true}, isPublished: {type: Boolean, default: false}, or
const hackathonSchema = new mongoose.Schema({
hackathonId: {type: Number, required: true},
uuid: {type: String, required: true},
data: {type: Object, required: true},
isPublished: {type: Boolean, default: false},
organisers: [String],
volunteers: [String],
participants: [String],
mentors: [String]
});
export default mongoose.model('Hackathon', hackathonSchema);
我想找回所有那些
长度:
( organisers + volunteers + participants +mentors ) >= 500
或是任何有价值的东西
我发现答案是这样的,但在猫鼬中不是这样的只需将大小加在一起: 使用MongoDB 3.4或更高版本 或者在没有该运算符的早期版本中
Model.aggregate([
{ "$redact": {
"$cond": {
"if": {
"$gt": [
{ "$add": [
{ "$size": { "$ifNull": [ "$organisers", [] ] } },
{ "$size": { "$ifNull": [ "$volunteers", [] ] } },
{ "$size": { "$ifNull": [ "$participants", [] ] } },
{ "$size": { "$ifNull": [ "$mentors", [] ] } }
]},
500
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}},
{ "$project": { "_id": 1 } }
],function(err,results) {
})
在这两种方法中,您都将其用作集合中文档的逻辑筛选器。作为本机运算符,这是处理此情况的最快方法
在内部,它唯一的参数是哪个是“三元”操作(if/then/else)来计算和返回值。因此,当条件的结果为“如果”
导致true
,“那么”
操作是$$保留
文档,或者“else”
从结果中删除文档
基于版本的不同方法有:
- 为了制作一个“大”数组并返回
- 或者对每个数组和值使用,以获得总数
\u id
字段,那么只需添加一个stage,与常规查询投影一样,您可以提供要返回的属性列表。在这种情况下,仅显示\u id
字段
您可以首先使用$match
向基本查询添加一些关于最小数组长度的假设,但这将是一个假设,而不是绝对事实
作为记录,您可以使用该子句运行完全相同的操作,但由于该操作符使用JavaScript求值,而不是像聚合框架操作那样本机实现,因此它确实会对性能产生显著影响,因为它运行较慢:
Model.find({ "$where": function() {
return [
...this.organisers,
...this.volunteers,
...this.participants,
...this.mentors
].length > 500
}).select({ "_id": 1 }).exec(function(err,results) {
})
因此,尽管与聚合管道结构的DSL形式相比,它可能“看起来很漂亮”,但性能损失并不值得。只有当您的MongoDB版本缺少操作员时,才应该这样做,这将是MongoDB 2.6之前的版本。在这种情况下,您可能还应该出于其他原因更新MongoDB。这里的“修订”操作符实现了什么?我能理解其余的@有一个链接。我实际上是在你打字的时候添加了解释。现在,如果我只想检索一个列表Hackathon id
id
,而不是整个模型,该如何修改这个查询?如果它是一个find()
query,我会做类似find({id},…query)
;“这里也一样吗?”博拉加巴补充道。对你来说,这可能是一个很好的练习。使用MongoDB时,您需要知道如何使用这些工具。
Model.find({ "$where": function() {
return [
...this.organisers,
...this.volunteers,
...this.participants,
...this.mentors
].length > 500
}).select({ "_id": 1 }).exec(function(err,results) {
})