-1

I have two separate MongoDB collections stock and sold.

I'd like to get all the entries in sold of certain stock types. The information for stock type is in another collection called stock, both have unique stock indexes.

Since I can't join in MongoDB, I am trying to query both collections. What is the best way to go about this?

I have tried:

cursor1 = db.stock.find({
    "$or": [
        {“Stock_Type": 1},
        {“Stock_Type": 2},
        {“Stock_Type": 3},
        ]
    })

stock_id = []

for i in cursor:
    stock_id.append(i.Stock_Index)

cursor2 = db.sold.find({
    "$and": [
        {“Stock_Index": {"$in": stock_id}},
        {“Month”: “February},
        {“Category”:5}
        ]
    })

In the above case I get an internal server error:

AttributeError: 'dict' object has no attribute 'Stock_Index'

Thanks in advance for any responses.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
noob
  • 5,954
  • 6
  • 20
  • 32

1 Answers1

1

Every item in a pymongo cursor is MongoDB document which is represented as a dictionary in Python. You cannot use dot notation to access items in dictionaries - instead, use:

stock_id = []
for i in cursor:
    stock_id.append(i["Stock_Index"])

Or, with a list comprehension:

stock_id = [i["Stock_Index"] for i in cursor]

As a side note, you could not have made it in a single query since you cannot join two collections in one query, please see more at:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Hi, thank you for your very helpful response :) I am having another issue where an empty list [] is returned, however when I print the length of the list before returning, the server always prints a number greater than 1. I am pretty sure the list should not be empty, this is really odd. – noob Mar 27 '16 at 17:03