Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays MongoDB mongoose$查找不在数组中。_Arrays_Mongodb_Mongoose_Aggregate - Fatal编程技术网

Arrays MongoDB mongoose$查找不在数组中。

Arrays MongoDB mongoose$查找不在数组中。,arrays,mongodb,mongoose,aggregate,Arrays,Mongodb,Mongoose,Aggregate,我使用以下查询: Collection .aggregate([ { $project : { follow_count: {$size: { "$ifNull": [ "$follow_users", [] ] } } } }, { $lookup: {from: 'models', localField: '_id', foreignField: '_id', as: 'model'}}, ]) 要获取此类JSON,请执行以下操作: [

我使用以下查询:

Collection
    .aggregate([
    {
        $project : { follow_count: {$size: { "$ifNull": [ "$follow_users", [] ] } } }
    },
    { $lookup: {from: 'models', localField: '_id', foreignField: '_id', as: 'model'}},
])
要获取此类JSON,请执行以下操作:

[
  {
    "_id": "1234565434567",
    "follow_count": 3,
    "model": [
      {
        "_id": "1234565434567",
        "make": "Make1",
        "name": "Model1",
        "price": 15200,
      }
    ]
  },
  {
    "_id": "123456789",
    "follow_count": 2,
    "model": [
      {
        "_id": "123456789",
        "make": "Make2",
        "name": "Model2",
        "price": 12000,
      }
    ]
  }
]
有没有办法不将$lookup结果推送到一个数组中以获得类似的JSON? 我更喜欢在查询之后不使用循环,所以我正在寻找一种优化的方法

[
  {
    "_id": "1234565434567",
    "follow_count": 3,
    "make": "Make1",
    "name": "Model1",
    "price": 15200,
  },
  {
    "_id": "123456789",
    "follow_count": 2,
    "make": "Make2",
    "name": "Model2",
    "price": 12000,
  }
]

您可以在3.6版本中使用
$mergeObject
运算符

$mergeObject
将合并的集合字段与其他字段合并,然后是
$replaceRoot
,将合并的文档提升到顶层

$project
,排除以删除
模型
字段

$lookup

 [
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          {
            "$arrayElemAt": [
              "$model",
              0
            ]
          },
          "$$ROOT"
        ]
      }
    }
  },
  {
    "$project": {
      "model": 0
    }
  }
]

尝试使用$unwind或$project