mongodb - mongodb 聚合以查找、计数和投影独特的文档网络
问题描述
以下是样本集。
col1:
"_id" : ObjectId("5ec293782bc00b43b463b67c")
"status" : ["running"],
"name" : "name1 ",
"dcode" : "dc001",
"address" : "address1",
"city" : "city1"
col2:
"_id" : ObjectId("5ec296182bc00b43b463b68f"),
"scode" : ObjectId("5ec2933df6079743c0a2a1f8"),
"ycode" : ObjectId("5ec293782bc00b43b463b67c"),
"city" : "city1",
"lockedDate" : ISODate("2020-05-20T00:00:00Z"),
"_id" : ObjectId("5ec296182bc00b43b463688b"),
"scode" : ObjectId("5ec2933df6079743c0a2a1ff"),
"ycode" : ObjectId("5ec293782bc00b43b463b67c"),
"city" : "city1",
"lockedDate" : ISODate("2020-05-20T00:00:00Z"),
"_id" : ObjectId("5ec296182bc00b43b44fc6cb"),
"scode" :null,
"ycode" : ObjectId("5ec293782bc00b43b463b67c"),
"city" : "city1",
"lockedDate" : ISODate("2020-05-20T00:00:00Z"),
问题陈述:
我想根据 scode 为 != null 的 ycode 显示 col1 中的名称和 col2 中的文档数
尝试过:
db.col1.aggregate([
{'$match':{
city:'city1'
}
},
{
$lookup:
{
from: "col2",
let: {
ycode: "$_id",city:'$city'
},
pipeline: [
{
$match: {
scode:{'$ne':null},
lockedDate:ISODate("2020-05-20T00:00:00Z"),
$expr: {
$and: [
{
$eq: [
"$ycode",
"$$ycode"
]
},
{
$eq: [
"$city",
"$$city"
]
}
]
},
},
},
], as: "col2"
}
},
{'$unwind':'$col2'},
{'$count':'ycode'},
{
$project: {
name: 1,
status: 1,
}
},
])
现在这个查询的问题是它要么显示计数,要么显示名称和状态,即如果我以当前格式运行此查询,{}
如果我删除它会给出,{'$count':'ycode'}
那么它会投影值但不给出计数,如果我删除$project
然后我做得到计数{ycode:2}
,但项目不起作用,但我想在结果中实现两者。有什么建议么
ORM:猫鼬 v>5,mongodb v 4.0
解决方案
您可以尝试以下查询:
db.col1.aggregate([
{ "$match": { city: "city1" } },
{
$lookup: {
from: "col2",
let: { id: "$_id", city: "$city" }, /** Create local variables from fields of `col1` but not from `col2` */
pipeline: [
{
$match: { scode: { "$ne": null }, lockedDate: ISODate("2020-05-20T00:00:00Z"),
$expr: { $and: [ { $eq: [ "$ycode", "$$id" ] }, { $eq: [ "$city", "$$city" ] } ] }
}
},
{ $project: { _id: 1 } } // Optional, But as we just need count but not the entire doc, holding just `_id` helps in reduce size of doc
],
as: "col2" // will be an array either empty (If no match found) or array of objects
}
},
{
$project: { _id: 0, name: 1, countOfCol2: { $size: "$col2" } }
}
])
测试: mongoplayground
推荐阅读
- sql - PostgreSQL 检查数组中的至少一项是否在字符串中
- node.js - 如何保护 Web API 免受未经授权的使用
- javascript - 如何使用基于当前 url 的 javascript 在 jsp 文件中设置 div 项的活动菜单状态?
- pandas - 如何使用源 DataFrame 中满足条件的值更新目标 DataFrame?
- javascript - Vue 导航守卫在 localStorage 硬刷新之前运行
- react-native - 如何在 iOS 中使用 resizeMode 反应原生?
- android - 谷歌脚本:在一个项目中使用 MIT App Inventor 的多个 doPost
- go - 无法使用“go mod vendor”从 Kubernetes 集群连接到 Go 代理
- python - 通过过滤 sql 中的特定变量值从 cursor.execute(sql) 获取数据到 python 列表
- oracle - 如何创建批处理以将 Oracle 数据库数据上传到 AWS Data Exchange?