我正在尝试在查询中的对象数组中搜索特定值。我如何从已经进行查询的以下行中获取用户“ taylor”?
我已经尝试过$elemMatch :{user:"taylor"}
,但这只会返回Taylor之后的所有帐户。我只需要得到泰勒的用户名starman的关注即可。上下文:我正在做一个if语句来搜索是否有人已经在关注某个帐户,因此我可以重新发送json消息,说“您已经关注他们!”停止重复的关注者。
{
"success": true,
"user": {
"name": "Kyle",
"username": "starman",
"bio": "Why yes I am a groupie, how did you know?",
"avatar": "https://i.imgur.com/YfyWjq4.gif",
"phone": "6788456456",
"followers": [],
"following": [
{
"user": "taylor"
},
{
"user": "trevor"
}
]
}
}
答案 0 :(得分:0)
尝试此查询
db.testers.aggregate([
{ $match: {"user.following.user":"taylor"} } ,
{ "$addFields": {
"user.following":
{
"$filter": {
"input": "$user.following",
"as": "sn",
"cond": {
"$and": [
{ "$eq": [ "$$sn.user", "taylor" ] },
]
}
}
}
}},
])