mongodb pymongo.errors.OperationFailure:pipeline“数组的每个元素都必须是对象

3b6akqbq  于 2023-02-21  发布在  Go
关注(0)|答案(1)|浏览(99)

我的查询

db.sections.aggregate([ { "$lookup": { "from": "faqs", "localField": "_id", "foreignField": "section_id",  "as": "faq","pipeline": [{ $project: { _id: 1, question: 1,answer:1 } }] } }]);

答复

[
  {
    _id: '63e4a4d9304637ec1b578136',
    name: 'vaaaaaq',
    is_active: true,
    created_by: 'string',
    updated_by: 'string',
    created_at: '2023-02-09T07:46:33.794565',
    updated_at: ISODate("2023-02-09T12:21:03.136Z"),
    faq: [
      {
        _id: '63e4cd7a1fdf5ee828bb33b9',
        question: 'what is',
        answer: 'it is'
      },
      {
        _id: '63e628fc8f3fb951cddfac02',
        question: 'wwww',
        answer: 'ssss'
      }
    ]
  },
  {
    _id: '63e4c2056f1845a3fc2180c5',
    name: 'new section',
    is_active: true,
    created_by: null,
    updated_by: null,
    created_at: '2023-02-09T09:51:01.877699',
    updated_at: '2023-02-09T09:51:01.877702',
    faq: [
      {
        _id: '63e7bfc9865085b29e65a97d',
        question: 'it is new ques',
        answer: 'nothonv'
      }
    ]
  }
]

上面是我的mongoshell数据,它正在获取两个对象。

在Python中

sections_data = {
   
   "$lookup": {
         "from": "faqs", 
         "localField": "_id", 
         "foreignField": "section_id", 
         "as": "data",
         "pipeline":[
            {
               "$project":{
                  "_id": 1,
                   "question": 1,
                   "answer":1 
                   }
            }
         ]
   }
}

pipeline=[
   sections_data,
   
]

async def get_list():
   results =  db['sections'].aggregate(pipeline)
   results = await results.to_list(1000)
   for r in results:
      return r

这是我的代码,它只返回一组数据response

{
  "_id": "63e4a4d9304637ec1b578136",
  "name": "vaaaaaq",
  "is_active": true,
  "created_by": "string",
  "updated_by": "string",
  "created_at": "2023-02-09T07:46:33.794565",
  "updated_at": "2023-02-09T12:21:03.136000",
  "data": [
    {
      "_id": "63e4cd7a1fdf5ee828bb33b9",
      "question": "what is",
      "answer": "it is"
    },
    {
      "_id": "63e628fc8f3fb951cddfac02",
      "question": "wwww",
      "answer": "ssss"
    }
  ]
}

在section_data中,如果i包含在数组中,

节数据=[{}]

这个错误是来自我错过的地方,以及如何解决这个问题。感谢您的输入。

cbjzeqam

cbjzeqam1#

results =  await db['sections'].aggregate(pipeline).to_list(1000)

相关问题