let say post has multi tag array field :
{
"id": 1,
"title": "Tv for sale",
"city":"doha",
"tags": ["doha", "tv", "sale", "used" ]
}, {
"id": 2,
"title": "flat for rent",
"city":"dubai",
"tags": ["dubai", "flat", "rent" ]
}
and user subscriptions as follow:
{
"id": 1,
"name": "user1",
"subscriptions": [["doha", "tv", "used"],["dubai", "flat", "sale"]]
}
how can I in Mongodb get the list of posts based on user subscriptions. so the user gets the posts where any of his subscriptions is fully included in post tags.
in this case, only post with id:1
will be returned
Thanks
CodePudding user response:
There are lots of ways this could be done. Here's one way.
db.users.aggregate([
{
"$lookup": {
"from": "posts",
"let": {
"subs": "$subscriptions"
},
"as": "posts",
"pipeline": [
{
"$match": {
"$expr": {
"$reduce": {
"input": "$$subs",
"initialValue": false,
"in": {
"$or": [
"$$value",
{"$setIsSubset": ["$$this", "$tags"]}
]
}
}
}
}
}
]
}
}
])
Try it on mongoplayground.net.