Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.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
Node.js MongoDB从$filter返回一个对象_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js MongoDB从$filter返回一个对象

Node.js MongoDB从$filter返回一个对象,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,使用者字段是包含两个对象的数组。使用$filter,一个对象被删除,但我需要消费者在最后成为一个对象,但现在它是带有一个对象的数组。我尝试了$arrayToObject,但无法开始工作。如何将消费者归为对象 { $project: { messages: 1, authors: { $concatArrays: ["$userName", "$storeName"] }, consumer: { $filter

使用者字段是包含两个对象的数组。使用
$filter
,一个对象被删除,但我需要消费者在最后成为一个对象,但现在它是带有一个对象的数组。我尝试了
$arrayToObject
,但无法开始工作。如何将消费者归为对象

   {
      $project: {
        messages: 1,
        authors: { $concatArrays: ["$userName", "$storeName"] },
        consumer: {
          $filter: {
            input: { $concatArrays: ["$userName", "$storeName"] },
            as: "authors",
            cond: { $ne: ["$$authors._id", req.user._id] }
          }
        },
      }
    }
试试这个:

{
    $project: {
        messages: 1,
            authors: { $concatArrays: ["$userName", "$storeName"] },
        consumer: {
            $arrayElemAt: [{
                $filter: {
                    input: { $concatArrays: ["$userName", "$storeName"] },
                    as: "authors",
                    cond: { $ne: ["$$authors._id", req.user._id] }
                }
            }, 0]
        }
    }
}

您可以直接在
$filter
之后使用,而不是在
$unwind
之后使用附加的阶段,
$filter
通常会返回匹配对象的数组,或者如果没有匹配的对象,则返回
[]
,因此如果您使用
$unwind
则需要使用它
{$unwind:{path:“$consumer”,preserveNullAndEmptyArrays:true}
否则在最终聚合响应中有可能丢失文档(其具有
消费者
作为
[]
),请在此处阅读更多相关信息:。因此,我更喜欢
$arrayElemAt
而不是
$unwind

您需要的$unwind@Yahya非常感谢。