简体   繁体   English

mongomock 聚合 $lookup 不能像真正的 mongo db (python) 那样解析集合名称

[英]mongomock aggregate $lookup does not resolve collection name like real mongo db (python)

I have a simple aggregate lookup query like this:我有一个简单的聚合查找查询,如下所示:

cursor = db.my_db['shop'].aggregate([
        {
            '$lookup':
                {
                    'from': 'customer',
                    'localField': 'in_shop',
                    'foreignField': '_id',
                    'as': 'joined_customers'
                }
        }
    ])

Note that this query uses the other collection customer it its from clause.请注意,此查询使用其from子句的其他集合customer This query works perfectly fine against an actual mongo db but not against my mongomock.MognoClient object.此查询对实际的 mongo db 非常有效,但对我的mongomock.MognoClient object 无效。

To get it to work with the mongomock I need to add the database prefix to the query like so:为了让它与mongomock一起工作,我需要将数据库前缀添加到查询中,如下所示:

cursor = db.my_db['shop'].aggregate([
        {
            '$lookup':
                {
                    'from': 'my_db.customer',
                    'localField': 'in_shop',
                    'foreignField': '_id',
                    'as': 'joined_customers'
                }
        }
    ])

However if I do that this query does not work against the actual mongo DB anymore.但是,如果我这样做,则此查询不再适用于实际的 mongo DB。 What is going wrong here?这里出了什么问题? I can't create code that works on both the mock and the actual db.我无法创建适用于模拟和实际数据库的代码。

If I don't include the database name the mock does not find the other collection to join it.如果我不包含数据库名称,则模拟不会找到其他集合来加入它。 To be clear both queries work perfectly fine on their respective "systems" and both collections can be queried in the mock on their own.需要明确的是,这两个查询在各自的“系统”上都可以正常工作,并且 collections 都可以在模拟中自行查询。 Just the lookup of the customer collection does not work correctly in the mongomock if the from clause does not include the database name prefix.如果from子句不包含数据库名称前缀,则仅在 mongomock 中查找customer集合无法正常工作。

I found the issue.我发现了这个问题。 I mocked the imported package instead of the database in the imported package.我模拟了导入的 package 而不是导入的 package 中的数据库。 This has effectively resulted in something like Database(Database(Collection())) whilst it should be only Database(Collection()) .这实际上导致了类似Database(Database(Collection()))的东西,而它应该只是Database(Collection()) So it did not have anything to do with mongomock after all.所以它毕竟与mongomock没有任何关系。

I guess the learning is that nested databases are possible and since they behave just like variables in an imported package the error did not show until an internal function tried to cross-reference another Collection.我猜想学习的是嵌套数据库是可能的,因为它们的行为就像导入的 package 中的变量一样,直到内部 function 尝试交叉引用另一个集合时才显示错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM