Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongodb – match field ( array of strings ) with query of multi lists of strings

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

in this case, only post with id:1 will be returned

Thanks

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading