Javascript 如何比较两个数组并获得匹配的输出?
在我的收藏中,我有一个Javascript 如何比较两个数组并获得匹配的输出?,javascript,node.js,arrays,mongodb,mongoose,Javascript,Node.js,Arrays,Mongodb,Mongoose,在我的收藏中,我有一个类别数组,如下所示 我收到另一个数组到我的API,如下所示 array = ['Chess','Rugby']; 我想在数据库查询中添加一个条件,使类别对象中的catName字段存在于数组中 目前,我正在使用以下代码获得结果: postSchemaModel.aggregate([{ "$geoNear": { "near": { "type": &quo
类别
数组,如下所示
我收到另一个数组到我的API,如下所示
array = ['Chess','Rugby'];
我想在数据库查询中添加一个条件,使类别
对象中的catName
字段存在于数组
中
目前,我正在使用以下代码获得结果:
postSchemaModel.aggregate([{
"$geoNear": {
"near": { "type": "Point", "coordinates": [parseFloat(long), parseFloat(lat), ] },
"distanceField": "dist.calculated",
"maxDistance": parseInt(maxDistance),
"includeLocs": "dist.location",
"spherical": true
}
},
{ "$match": { "$or": [{ "typology": "post" }, { "typology": "chat_group" }] } },
{
"$match": {
"createdAt": {
"$gte": '2020-07-15 23:54:38.673665',
"$lt": '2020-06-15 23:54:38.673665'
}
}
},
{ "$limit": limit },
{ "$skip": startIndex },
{ "$sort": { "createdAt": -1 } },
{
"$lookup": {
"from": userSchemaModel.collection.name,
"localField": "user_id",
"foreignField": "_id",
"as": "user_id"
}
},
{
"$project": {
"post_data": 1,
"likes": 1,
"commentsCount": 1,
"post_img": 1,
"isUserLiked": 1,
"usersLiked": 1,
'exp_date': 1,
"has_img": 1,
"user_id": {
"img": "$user_id.img",
"_id": "$user_id._id",
"user_name": "$user_id.user_name",
"bday": "$user_id.bday",
"imagesource": "$user_id.imagesource",
"fb_url": "$user_id.fb_url",
},
"typology": 1,
"geometry": 1,
"category": 1,
"created": 1,
"createdAt": 1,
"updatedAt": 1,
}
},
]).then(async function(posts) {
//some code here
}
});
更新:样本输出
如果只想获得true
/false
结果,则可以使用方法:
category.some(element=>array.includes(element.catName))
如果您想要获得一个包含所有类别
对象的数组,这些对象的cat名称也存在于数组中
中,那么您可以使用以下方法:
category.filter(element=>array.includes(element.catName))
如果您的代码中有一个名为数组
的对象,并且您希望在类别数组中查找猫名位于数组
中,则可以将条件添加到$match
阶段:
{“$match”:{“$or”:[{“类型学”:“post”},{“类型学”:“chat_group”}]},category.catName:{$in:array}
使用另一个$match
和“$elemMatch”
解决了问题
"$match": {
"category": { "$elemMatch": { "catName": "Rugby", "catName": "Carrom" } },
}
category
是一个对象数组<代码>数组在您的示例中是一个字符串数组。你能举一个结果数组的例子吗?@Yos添加了一个我目前得到的示例结果,你说的是“我正在向我的API接收另一个数组,如下面的array=['category1'、'category2'、'category3'];
”array
和category
之间有什么联系?@Yos在我的postSchemaModel
中有一个数组“category”。我想检查该数组是否包含array=['Chess','Rugby']中的任何元素代码>并将它们带到我的输出Hanks!。但是你能建议我如何在上面的集合管道中使用这个吗?你需要在你的问题中更具体一些,你没有提到最后一个条件。此外,还不清楚数据库/API响应中的array
在哪里/是什么。
"$match": {
"category": { "$elemMatch": { "catName": "Rugby", "catName": "Carrom" } },
}