问题
I am using mongoDB I use query
db.getCollection('managements').find({'managers.role':"HR"},{'managers.$':1})
I get result as below
/* 1 */
{
"_id" : ObjectId("1"),
"managers" : [
{
"id" : "100",
"role" : "HR"
},
{
"id" : "101",
"role" : "ADMIN"
},
{
"id" : "102",
"role" : "ADMIN"
}
]
}
/* 2 */
{
"_id" : ObjectId("2"),
"managers" : [
{
"id" : "104",
"role" : "ADMIN"
},
{
"id" : "105",
"role" : "HR"
}
,
{
"id" : "106",
"role" : "HR"
}
,
{
"id" : "107",
"role" : "HR"
}
]
}
Now I want to get individual records where role is HR and count is more than one, like
{ id:2
count : 3}
回答1:
You can use below aggregation
db.collection.aggregate([
{ "$match": {
"$expr": {
"$gte": [
{ "$size": {
"$filter": {
"input": "$managers",
"cond": { "$eq": ["$$this.role", "HR"] }
}
}},
2
]
}
}},
{ "$addFields": {
"count": {
"$size": {
"$filter": {
"input": "$managers",
"cond": { "$eq": ["$$this.role", "HR"] }
}
}
}
}}
])
来源:https://stackoverflow.com/questions/59786240/mongodb-get-individual-count-from-sudocuments-with-comparison-operations