【问题标题】:How can i insert this JSON file into a MongoDB collection?如何将此 JSON 文件插入 MongoDB 集合?
【发布时间】:2021-05-13 10:45:19
【问题描述】:

我正在尝试将此对象插入到 mongo DB 集合中。我已经尝试了很多方法,但没有得到任何结果。我想知道这里是否有人可以帮助我。主要问题是在将项目数组传递到键 items 时。

JSON 文件与此类似:

{
  'code': 'iuhuilknlkn',
  'description': 'nllksnd',
  'currency': 'Mxn',
  'items': [
    {
      'item': {
        '_id': {
          '$oid': '60065d253ef6d468ced3603f'
        },
        'code': '2',
        'description': '22',
        'currency': 'Mxn',
        'MU': 'Hr',
        'sellingPrice': 1,
        'buyingPrice': 3,
        'supplier': None,
        'cid': '5fbd81b32b325e5ca15fe5c9',
        'itemAmount': 1,
        'itemProductPrice': 1,
        'itemAmountPrice': 1
      }
    },
    {
      'item': {
        '_id': {
          '$oid': '6011c18883a280ae0e5b8185'
        },
        'code': 'prb-001',
        'description': 'prueba 1 artículo',
        'currency': 'Mxn',
        'MU': 'Ser',
        'sellingPrice': 100.59,
        'buyingPrice': 12,
        'supplier': None,
        'cid': '5fbd81b32b325e5ca15fe5c9',
        'itemAmount': 1,
        'itemProductPrice': 100.59,
        'itemAmountPrice': 100.59
      }
    }
  ],
  'price': 101.59
}

我现在使用的代码如下:

productsM.insert({
               'code':newP['code'],
               'description':newP['description'],
               'currency' :newP['currency'],
               'items' : [([val for dic in newP['items'] for val in 
                         dic.values()])],
               'price' : newP['price'],
               'cid': csHe })

我得到的错误是下一个:

key '$oid' must not start with '$'

【问题讨论】:

标签: python json mongodb insert


【解决方案1】:

你的错误很清楚。只需从字典/json 中的 $oid 键中删除 $ 即可解决此问题。我认为您不能在键名中使用$,因为它们是为$in$regex 等运算符保留的。

我从$oid 键中删除了$,它就像一个魅力。我所做的只是:


data = {
  "code": "iuhuilknlkn",
  "description": "nllksnd",
  "currency": "Mxn",
  "items": [
    {
      "item": {
        "_id": {
          "oid": "60065d253ef6d468ced3603f"
        },
        "code": "2",
        "description": "22",
        "currency": "Mxn",
        "MU": "Hr",
        "sellingPrice": 1,
        "buyingPrice": 3,
        "supplier": None,
        "cid": "5fbd81b32b325e5ca15fe5c9",
        "itemAmount": 1,
        "itemProductPrice": 1,
        "itemAmountPrice": 1
      }
    },
    {
      "item": {
        "_id": {
          "oid": "6011c18883a280ae0e5b8185"
        },
        "code": "prb-001",
        "description": "prueba 1 artículo",
        "currency": "Mxn",
        "MU": "Ser",
        "sellingPrice": 100.59,
        "buyingPrice": 12,
        "supplier": None,
        "cid": "5fbd81b32b325e5ca15fe5c9",
        "itemAmount": 1,
        "itemProductPrice": 100.59,
        "itemAmountPrice": 100.59
      }
    }
  ],
  "price": 101.59
}

db.insert(data)


【讨论】:

    猜你喜欢
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2021-09-01
    • 2016-11-16
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多