我正在使用 MongoDB Aggregate 框架来查询用户集合。
这是下面的用户架构布局示例:
{
"_id" : ObjectId("XXXXXXXXXXXXXX367db"),
"updatedAt" : ISODate("2017-08-18T10:59:54.904Z"),
"createdAt" : ISODate("2017-08-18T10:59:54.904Z"),
"email" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef898e848adad8af88828e8683c18c8082" rel="noreferrer noopener nofollow">[email protected]</a>",
"firstName" : "Tianna.",
"gender" : "male",
"geometry" : {
"coordinates" : [
-6.26119,
53.35247
],
"_id" : ObjectId("5996c8a9a4d84d3639c367dc"),
"type" : "point"
},
"age" : 25,
"personalAttributes" : [
"ksjdnksajdna",
"ksjdssacasca",
"xz12nksajdna",
"xz12nksaxxna",
"xz12nksaxxxx",
"xz12nwwzwwwa",
"xz12nkslkmna",
]
}
这是聚合管道中概述的步骤。
1:使用 $geoNear 运算符对指定距离内的用户进行地理定位。
2:根据性别匹配用户。
db.getCollection('users').aggregate([
{
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [
-6.26030969999999,
53.3498053
]
},
"distanceField": "dist.calculated",
"spherical": true,
"maxDistance": 770000
}
},
{
"$match": {
"gender": "male"
}
}
])
我想要做的是传递另一个用户的personalAttributes数组并计算每个数组中匹配项的数量。它看起来像这样:
db.getCollection('users').aggregate([
{
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [
-6.26030969999999,
53.3498053
]
},
"distanceField": "dist.calculated",
"spherical": true,
"maxDistance": 770000
}
},
{
"$match": {
"gender": "male"
}
},
{
"$project": {
"_id": 1,
"gender": 1,
"firstName": 1,
"profileImage": 1
"personalAttributesMatches": {
//Pass in the users personalAttributes Array and count the number of matches and return all the data.
}
}
}
}
])
预期输出为
/* 1 */
{
"_id" : ObjectId("5996c8aaa4d84d3639c36a61"),
"firstName" : "Sharon",
"gender" : "male",
"personalAttributesMatches": 15
}
/* 2 */
{
"_id" : ObjectId("5996c9c41daf273658715fcf"),
"firstName" : "Hilton",
"gender" : "male",
"personalAttributesMatches": 11
}
/* 3 */
{
"_id" : ObjectId("5996c6d66f8910361b8232b5"),
"firstName" : "Eliezer",
"gender" : "male",
"personalAttributesMatches": 7
}
对此的见解将不胜感激!
最佳答案
您可以使用setIntersection表达式,因此您的项目阶段可能如下所示:
"$project": {
"_id": 1,
"gender": 1,
"firstName": 1,
"profileImage": 1,
"personalAttributesMatches": {
$size:{
$setIntersection: ["$personalAttributes", _other_persons_attributes_]
}
}
}
关于arrays - 如何计算另一个数组中一个数组中的匹配元素 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45760394/