为什么 Mongo 字符串比较将等效字符串读取为不等效? pymongo

Why is Mongo string comparison reading equivalent strings as inequivalent? pymongo

我正在使用 pymongo 搜索 MongoDB 文档,其中一个字段中的字符串值不等于另一个字段中的字符串值。我试过 $cmp、$strcasecmp、$ne 和 $eq,但它们都return认为看起来与我相同的字符串并不相同。

管道从集合与文档之间的连接开始,如下例所示:

# test collection:
[
 {'_id': '611868136', 'doc_type': 'way'},
 {'_id': '5792648632', 'doc_type': 'node'},
 {'_id': '611868133', 'doc_type': 'node'},
 {'_id': '1', 'doc_type': 'node'}
]

# refer_docs collection:
[
 {'_id': '8483444',
  'refs': [{'ref': '611868136', 'ref_type': 'way'},
           {'ref': '5792648632', 'ref_type': 'node'},
           {'ref': '611868133', 'ref_type': 'way'}],
  'doc_type': 'relation'}
]

现在,这是聚合:

import pymongo
mongo_client = MongoClient('localhost:27017')
osm_db = mongo_client.osm
refer_docs_col = osm_db["refer_docs"]

pipeline = [
    { "$unwind" : "$refs" },
    {
        "$lookup" : {
            "from" : "test",
            "localField" : "refs.ref",
            "foreignField" : "_id",
            "as" : "ref_doc"
        }
    },
    { "$match" : { "ref_doc" : { "$ne" : [] } } },
    { "$unwind" : "$ref_doc"},
    { "$match" : { "refs.ref_type" : { "$ne" : "$ref_doc.doc_type" } } },
    { "$project" : { "_id" : 1, "refs" : 1, "ref_doc.doc_type" : 1, 
                     "cmp" : { "$cmp" : [ "refs.ref_type",
                                          "ref_doc.doc_type" ] } } },
    { "$limit" : 1 }
]
[doc for doc in refer_docs_col.aggregate(pipeline)]

我希望return编辑以下文档:

[{'_id': '467676638',
 'refs': {'ref': '611868133', 'ref_type': 'way'},
 'ref_doc': {'doc_type': 'node'},
 'cmp': 1}]

但是,它还有 returns 文档,如下所示:

[{'_id': '8483444',
  'refs': {'ref': '611868136', 'ref_type': 'way'},
  'ref_doc': {'doc_type': 'way'},
  'cmp': 1},
 {'_id': '8483444',
  'refs': {'ref': '5792648632', 'ref_type': 'node'},
  'ref_doc': {'doc_type': 'node'},
  'cmp': 1},
 {'_id': '8483444',
  'refs': {'ref': '611868133', 'ref_type': 'way'},
  'ref_doc': {'doc_type': 'node'},
  'cmp': 1}]

注意比较字段(“refs.ref_type”、“ref_doc.doc_type”)在两种情况下(例如“节点”)显然包含等效值,但比较运算符 returns在所有情况下都是 1,表示第一个值大于第二个值。应该是return0,说明这两个值是等价的。

确认!为什么??

我在 $cmp 语句中忘记了几个美元符号,所以我比较的是字段名称的文字字符串而不是字段值。太明显了,呃。

pipeline = [
    { "$unwind" : "$refs" },
    {
        "$lookup" : {
            "from" : "test",
            "localField" : "refs.ref",
            "foreignField" : "_id",
            "as" : "ref_doc"
        }
    },
    { "$match" : { "ref_doc" : { "$ne" : [] } } },
    { "$unwind" : "$ref_doc"},
#     { "$match" : { "refs.ref_type" : { "$ne" : "$ref_doc.doc_type" } } },
    { "$project" : { "_id" : 1, "refs" : 1, "ref_doc.doc_type" : 1, 
                     "cmp" : { "$cmp" : [ "$refs.ref_type",
                                          "$ref_doc.doc_type" ] } } },
    { "$match" : { "cmp" : { "$ne" : 0 } } }
]
[doc for doc in refer_docs_col.aggregate(pipeline)]