问题
Background: I just learned the basics of databases and mongo this week.
I have a collection named 'orderstest' of 10K documents with the following basic form:
{
"_id": {
"$oid": "2309823082039482"
},
"Order": "12345678920000",
"Client": "Client Name Inc.",
"OrderUId": "3452-2342-9393-0100",
"OrderItems": [
{
"Client": "Client Name Inc.",
"Details": [
{
"Key": "EnterpriseCode",
"Value": "XYZ1000"
},
{
"Key": "AWSRegion",
"Value": "Frankfurt"
},
],
"ProductUId": "A90",
"OrderItemUId": "ABC1000",
}
],
"__v": 0
}
I have to create a python3 script to compare these entries with some AWS info. The 1st thing I need to do is to obtain all the documents whose ProductUId matches "A90" or "B90".
I ran this query in the mongo shell and it worked:
db.orderstest.find({
OrderItems:{$elemMatch: {
ProductUId:"A90"
}
}
})
But when I try to put this inside my script, it throws this error:
'OrderItems':{'$elemMatch': {
^
SyntaxError: invalid character in identifier
Also, I need to create the condition of all "A90" or "B90" which from reading the documentation and trying out tweaking a few things I was never able to implement. I should also state that I have gone through the MongoDB docs for several hours but it makes absolutely no sense to me, I guess due to my null experience with DBs in general.
回答1:
For "The 1st thing I need to do is to obtain all the documents whose ProductUId matches "A90" or "B90"."
.find({"OrderItems.ProductUId": {"$in":["A90","B90"]}})
Will work. Not sure why you're using $elemMatch, it doesn't seem necessary?
来源:https://stackoverflow.com/questions/51295266/how-to-correctly-query-a-mongodb-nested-document-with-python