Niall Cowperthwaite
Niall Cowperthwaite

Reputation: 105

PyMongo. How to filter the following data correctly?

My collection is looks like:

{
    ....
    "Main":{
        ...
        "Tags":[
            "tag1",
            "tag2",
            ...
        ]
    }
}

I am given a list of tags, the goal is to find all objects from the collection such that all tags from the list is in the object's list of tags. What is the correct and simplest way to do that?

Upvotes: 2

Views: 930

Answers (2)

MauriRamone
MauriRamone

Reputation: 503

Another alternative using python and the pymongo driver: Suppose you have the database "DB" and the collection "COLECTION". To get all the documents that contain the tags "tag1" and "tag2", do the following...

from pymongo import MongoClient

def main():
    mongoClient = MongoClient('mongodb://IP:PORT')
    db = mongoClient.DB
    collection = db.COLECTION

    objects = collection.find({"Main.Tags": {$all: ["tag1", "tag2"]}})

    for doc in objects:
        print doc[_id]      

if __name__ == "__main__":
        main()

The above example will display the _id of the searched documents.

Regards!

Upvotes: 2

Niall Cowperthwaite
Niall Cowperthwaite

Reputation: 105

I found the solution.

filter[0]['$match']['Main.Tags']['$all'] = searced_tags_list

Upvotes: 0

Related Questions