ss1111
ss1111

Reputation: 249

PyMongo - Searching Values of All Sub-Documents

I have the following entries in MongoDB about different drinks that I inserted through a Python script using the insert.one() command:

{
    "_id" : ObjectId('ffffffffffffffffff'),
    "Type" : "Juice"
    "Drinks" : {"Lemonade",
                "Apple Juice",
                "Orange Juice"
               }
 }
{
    "_id" : ObjectId('aaaaaaaaaaaaaaaaaa'),
    "Type" : "Alcohol"
    "Drinks" : {"Rum",
                "Whiskey",
                "Vodka"
               }
 }

I want to input the string Whiskey in Python and I would like to extract just the type of drink:

Alcohol

How can I go about doing this? Has there been another similar question that was answered? I am having trouble with searching all values of "Drinks" in both entries and then returning just the "Type".

I found this related question: PyMongo- selecting sub-documents from collection by regex and also this: How to get all sub-documents with a certain value of a certain field? But I could not figure out how to apply those concepts to my problem/could not figure out how to write those out in Python.

Upvotes: 0

Views: 194

Answers (1)

Gaurav Kumar Singh
Gaurav Kumar Singh

Reputation: 1570

You can use following query for this

db.collection.findOne({Drinks: 'Whiskey'}, {Type: 1})

Upvotes: 1

Related Questions