如何组合对象数组 mongodb

how to combine array of object result in mongodb

如何将匹配文档的子文档合并为一个并 return 将其合并为一个对象数组?我试过 $group 但似乎没有用。

我的查询(这个return对象数组在这种情况下有两个)

User.find({
      'business_details.business_location': {
        $near: coords,
        $maxDistance: maxDistance
      },
      'deal_details.deals_expired_date': {
        $gte: new Date()
      }
    }, {
      'deal_details': 1
    }).limit(limit).exec(function(err, locations) {
      if (err) {
        return res.status(500).json(err)
      }
console.log(locations) 

console.log(位置)结果 // 给我下面的结果

[{
  _id: 55 c0b8c62fd875a93c8ff7ea, // first document 
  deal_details: [{
    deals_location: '101.6833,3.1333',
    deals_price: 12.12 // 1st deal 
  }, {
    deals_location: '101.6833,3.1333',
    deals_price: 34.3 // 2nd deal 
  }],
  business_details: {}
}, {
  _id: 55 a79898e0268bc40e62cd3a, // second document 
  deal_details: [{
    deals_location: '101.6833,3.1333',
    deals_price: 12.12 // 3rd deal 
  }, {
    deals_location: '101.6833,3.1333',
    deals_price: 34.78 // 4th deal 
  }, {
    deals_location: '101.6833,3.1333',
    deals_price: 34.32 // 5th deal
  }],
  business_details: {}
}]

我想做的是将这两个 deal_details 字段组合在一起并 return 它作为一个对象数组。它将在 一个 对象数组中包含 5 个交易,而不是两个单独的对象数组。

我已经尝试在我的后端 (nodejs) 中通过使用 concat 或 push 来完成它,但是当有超过 2 个匹配文档时我无法将它们连接在一起,有什么方法可以合并所有匹配文档和 return 合二为一?就像我上面提到的那样?

您可以将它们与 reduce 合并:

locations = locations.reduce(function(prev, location){
    previous = prev.concat(location.deal_details)
    return previous
},[])

您可能在这里缺少的是 $unwind 管道阶段,这是您通常用于 "de-normalize" 数组内容的阶段,尤其是当您的分组操作打算跨查询结果中的文档工作时:

User.aggregate(
    [
        // Your basic query conditions
        { "$match": {
            "business_details.business_location": {
                "$near": coords,
                "$maxDistance": maxDistance
            },
            "deal_details.deals_expired_date": {
            "$gte": new Date()
        }},

        // Limit query results here
        { "$limit": limit },

        // Unwind the array
        { "$unwind": "$deal_details" },

        // Group on the common location
        { "$group": {
             "_id": "$deal_details.deals_location",
             "prices": {
                 "$push": "$deal_details.deals_price"
             }
        }}
    ],
    function(err,results) {
        if (err) throw err;
        console.log(JSON.stringify(results,undefined,2));
    }
);

输出如下:

{
    "_id": "101.6833,3.1333",
    "prices": [
        12.12,
        34.3,
        12.12,
        34.78,
        34.32
    ]
}

取决于实际匹配分组的文档数。

或者,您可能想查看 $geoNear 管道阶段,它提供了更多控制,尤其是在处理数组中的内容时。

另请注意,对于数组中的 "location" 数据,此处仅考虑 "nearest" 结果,而不考虑数组内容的 "all"。所以数组中的其他项实际上可能不是 "near" 查询点。这更多是一种设计考虑,因为您执行的任何查询操作都需要考虑这一点。