将字符串变量传递到 pymongo 查询中



我正在尝试抓取信息数据库,但查询时遇到问题。以下是MongoDB中的基本数据库设置:

{
  "ID": 346,
  "data": [
    {
      "number": "23",
      "name": "Winnie"
    },
    {
      "number": "12",
      "name": "Finn"
    },
    {
      "number": "99",
      "name": "Todd"
    }
  ]
}

{
  "ID": 346,
  "data": [
    {
      "number": "12",
      "name": "Ram"
    },
    {
      "number": "34",
      "name": "Greg"
    },
    {
      "number": "155",
      "name": "Arnie"
    }
  ]
}

相关的Python代码如下:

import pymongo
import json
import io
import sys
from bson.json_util import dumps
from pymongo import MongoClient
stringArr = ['"23"', '"12"', '"155"']
for x in range(0, len(stringArr))
print(collection.find({"data.number" :  stringArr[x]}).count())

当我输入collection.find({"data.number" : "23"}).count()时,我返回了正确数量的条目,其中"23"作为数据中的数字,因此我认为我在 Python 中查找的语法搞砸了,可能与变量是一个字符串有关,但我对 MongoDB 相当缺乏经验,更不用说 PyMongo了。任何建议将不胜感激!

$elemMatch运算符用于匹配属于 BSON 文档的数组字段中包含的值。

根据上述问题中提到的描述,请尝试在MongoDB shell中执行以下原始查询。

    db.collection.find({
    data: {
        $elemMatch: {
            number: {
                $in: ["23", "12", "155"]
            }
        }
    }
})

最新更新