本文介绍了如何使用python正确查询MongoDB嵌套文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:本周我刚刚学习了数据库和mongo的基础知识.

Background: I just learned the basics of databases and mongo this week.

我有一个名为"orderstest"的10K文档,其基本格式如下:

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
}

我必须创建一个python3脚本来将这些条目与一些AWS信息进行比较.我要做的第一件事是获取与ProductUId匹配的所有文档"A90"或"B90".

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".

我在mongo shell中运行了此查询,它起作用了:

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

此外,我需要创建所有"A90"或"B90"的条件,这些条件是通过阅读文档,并尝试调整一些我无法实现的功能.我还应该指出,我已经阅读了MongoDB文档数小时,但是对我来说这绝对没有意义,我想这是由于我对DB的空缺经验.

Also, I need to create the condition of all "A90" or "B90" which from reading thedocumentation 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.

推荐答案

对于"",我要做的第一件事是获取其ProductUId匹配"A90"或"B90"的所有文档. "

.find({"OrderItems.ProductUId": {"$in":["A90","B90"]}})

会工作.不知道为什么要使用$ elemMatch,这似乎没有必要吗?

Will work. Not sure why you're using $elemMatch, it doesn't seem necessary?

这篇关于如何使用python正确查询MongoDB嵌套文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:59