如何从数组内部打印一个对象以获取文档列表?

问题描述 投票:0回答:1

我有大约 50k 个文档,其中有很多字段,但此问题的重要文档如下所示:

"_id": ObjectId(""),
...
"item": "apple"
"properties" : [
 {
    "color": "red",
    "size" : "L",
    "status": "eatable"
 }
],
...

我想要打印的是看起来像 item+";"+properties.color 的行,同时保留我拥有的数据的完整性,并仅针对某些文档打印这些字段。目前,我唯一成功的事情是仅打印项目或整个数组“属性”,但我无法同时获取它们两者,也无法仅获取颜色。

db.getCollection("foods").find({properties:{$elemMatch:{color: {$in:["red", "green", "orange", "blue"]}}}})
.aggregate([
   { $unwind: {path:"$properties", preserveNullAndEmptyArrays: true}},
   ]).forEach(function(row){
       if(row.properties !== undefined) print (row.item + ";" + row.properties.color) })

这会给出一个错误,因为在聚合之前进行查找,但我真的不知道如何制作它,以便它只为符合该条件的行打印此内容(而且我也不知道是否$unwind 会弄乱我数据中的数组,或者如果它只是函数运行时的临时“分离”)。

我现在正在运行,只获取项目:

db.getCollection("foods").find({properties:{$elemMatch:{color: {$in:["red", "green", "orange", "blue"]}}}})
.forEach(
   function(row){
       print (row.item) 
   }
)

通过将 row.item 更改为 row.properties 我打印了完整的数组,但之后添加 .color 没有任何作用。

mongodb studio3t
1个回答
0
投票

不确定我是否理解,但是如何将数据准备到这样的查询中:

db.getCollection("foods").aggregate([
  {
    $match: {
      "properties.color": {
        $in: [
          "red",
          "green",
          "orange",
          "blue"
        ]
      }
    }
  },
  {
    $project: {
      _id: 0
      item: 1,
      color: {
        "$arrayElemAt": [
          "$properties.color",
          0
        ]
      }
    }
  }
])

示例此处

并获得像下面这样的 JSON,您可以轻松迭代并访问

color
item
属性。:

[
  {
    "color": "red",
    "item": "apple"
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.