我搜索了其他帖子,但是看起来不错的东西在这里无法工作。我需要你的建议。
这是我的文档在数据库中的样子,只有一个文档带有一系列标签。
我只需要查询计数器大于0的餐厅类型(这样最终结果将排除计数器0的任何类型)
我的模式
const tagsSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
details: {
restaurantTypeId: mongoose.Schema.Types.ObjectId,
restaurantTypes: [{
_id: mongoose.Schema.Types.ObjectId,
name: String,
counter: Number,
}],
foodTypeId: mongoose.Schema.Types.ObjectId,
foodTypes: [{
_id: mongoose.Schema.Types.ObjectId,
name: String,
counter: Number,
}]
}
});
我尝试过
tags.find({
'details.restaurantTypes.counter': {
$gt: 0
}
}, (err, data) => {
if (err) {
res.send(err);
}
res.json(data);
});
我知道了
[
{
"details": {
"restaurantTypeId": "5c01fb57497a896d50f49877",
"restaurantTypes": [
{
"_id": "5c01fb57497a896d50f49879",
"name": "Asian",
"counter": 1
},
{
"_id": "5c01fb57497a896d50f4987a",
"name": "Bakery",
"counter": 0
},
{
"_id": "5c01fb57497a896d50f4987b",
"name": "Barbecue",
"counter": 0
},
{
"_id": "5c01fb57497a896d50f4987c",
"name": "Bars & Pubs",
"counter": 0
},
{
"_id": "5c01fb57497a896d50f4987d",
"name": "Bistro",
"counter": 0
},
和
tags.find({
'details.restaurantTypes.counter': {
$gte: 1
}
}, (err, data) => {
if (err) {
res.send(err);
}
res.json(data);
});
给我相同的结果
答案 0 :(得分:1)
您可以使用聚合管道来过滤restaurantTypes
$match
-过滤餐厅$addFields
-通过计数器覆盖restaurantTypes和$filter
餐馆类型汇总管道
db.res.aggregate([
{$match: {"_id" : ObjectId("5c2187be640edfe094a3b946")}},
{$addFields:{"restaurantTypes" : {$filter : {input : "$restaurantTypes", as : "t", cond : {$ne : ["$$t.counter",0]}}}}}
])
答案 1 :(得分:0)
好的,我找到了答案,灵感来自萨拉瓦那。
这是使用汇总和过滤器的答案。
tags.aggregate([{
$match: {
"_id": mongoose.Types.ObjectId(id)
}
},
{
$project: {
"details.restaurantTypes": {
$filter: {
input: "$details.restaurantTypes",
as: "resType",
cond: {
$ne: ["$$resType.counter", 0]
}
}
}
}
}
]
这会给我结果
[
{
"_id": "5c01fb57497a896d50f49876",
"details": {
"restaurantTypes": [
{
"_id": "5c01fb57497a896d50f49879",
"name": "Asian",
"counter": 1
},
{
"_id": "5c01fb57497a896d50f498a6",
"name": "Thai",
"counter": 1
},
{
"_id": "5c01fb57497a896d50f498a8",
"name": "Western",
"counter": 1
}
]
}
}
]