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

标签 node.js mongodb mongoose

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

   {
      $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]
        }
    }
}

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

关于node.js - MongoDB 从 $filter 返回一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737371/

相关文章:

javascript - promise findOneAsync 变量 = {"isFulfilled":false ,"isRejected":false}?

node.js - 在 cordova(3.0.0) 中添加 blackberry10 平台显示 "Error: node cannot be found on the path. Aborting"

javascript - 我们可以在 Node JS 应用程序中使用带有 ejs(嵌入式 javascript)的 socket.io 而不是 html 页面吗?

javascript - 如何使用 node.js 在 selenium webdriver 中选择下拉值

javascript - 从集合中的数组中删除对象[性能/最佳实践/问题]

regex - 使用正则表达式在 mongodb 中搜索查询

node.js - 在 Node.js 应用程序中组织 View 文件

java - MongoDB 和 upsert 问题

javascript - mongoose 和 express.js 中的冲突日期

javascript - 使用 mongoose 中现有集合的一部分