Query an array in PyMongo

Viewed 359

I am trying to query an array using PyMongo and I am getting all the values instead of just the one matching 'A A'

Format of Array:

"tags": [
        {
            "tag": {
                "name": "A A"
                    }
         }
         ]

Python Code:

import pymongo
from pprint import pprint


myclient = pymongo.MongoClient("mongodb://00.00.00.0:27017")
mydb = myclient["dbName"]
mycol = mydb["thePage"]


for x in mycol.find({},{"_id": 0, "tags.tag.name":   "A A"}):
   pprint(x)

Result:

[{'tag': {'name': 'A A'}}, 
{'tag': {'name': 'B B'}},
{'tag': {'name': 'C C'}}]

Expected Result:

{'name': 'A A'}

I get the result I need using MongoDB:

db.dbName.where("tags.tag.name").eq("A A")
1 Answers

You need to deconstruct the array first. Try doing this:

mycol.aggregate([
    {'$unwind':'$tags'},
    {'$match': {
        'tags.tag.name':'A A',
    }},
    {'$project': {
        'tags.tag.name': 1, '_id': 0
    }},
])
Related