本文介绍了如何调用子数组中另一个集合中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个集合:一个称为 placestype_places.place 关联了一种地点类型(type_places),并且这可以关联来自 this(objects 数组)的一些对象.

I have 2 collections: one called places and type_places. a place has associated a type of place (type_places) and this can have associated some objects from this(objects array).

type_places
{
  "_id": "5fbc7cc705253c2da482023f",
  "type_place": "office",
  "objects": [
    {
      "_id": "5fbc7cc705253c2da48202saw",
      "name": "chair"
    },
    {
      "_id": "5fbc7cc705253c2da4820242",
      "name": "table"
    },
    {
      "_id": "5fbc7cc705253c2da482025f",
      "name": "desktop"
    }
  ]
}

places
{
    "_id": "5fbc7cc705253c2da482025f",
    "place": "Room 5",
    "type_place_id": "5fbc7cc705253c2da482023f", /*"office"*/
    "type_place_objects": [
      {
        "_id": "5fbc7cc705253c2da48202saw", /*chair*/
        "quantify": 4
      },
      {
        "_id": "5fbc7cc705253c2da482025f", /*desktop*/
        "quantify": 2
      }
    ]
  }

然后我希望当我查询 place 时,查询会显示我咨询的 place,它是什么样的地方 (type_place) 以及它所具有的那种类型的位置的对象

then I want that when I query a place, the query shows me the place that I am consulted, what kind of place it is (type_place) and what objects of that type of place it has

所需的输出:

{
  "_id": "5fbc7cc705253c2da482023f",
  "place": "Room 5",
  "type_place_objects": [
    {
      "_id": "5fbc7cc705253c2da48202saw",
      "name": "chair",
      "quantify": 4
    },
    {
      "_id": "5fbc7cc705253c2da482025f",
      "name": "desktop",
      "quantify": 2
    }
  ]
}

我正在尝试此操作但不起作用:

I am trying this but not works:

place.aggregate(
[
  {
    "$match": {"place":"Room 5"}
  },

  {
    "$lookup": {
      "from": "type_place",
      "localField": "type_place_id",
      "foreignField": "_id",
      "as": "type_place_objects"
    }
  },
  {
    "$sort": {
      "_id": -1
    }
  },
  {
    "$project": {
      "_id":1,
      "place":1,
      "type_place_objects": 1
    }
  }
  
])

怎么解决?

推荐答案

有很多种方法,一种方法是使用 $lookup,因为你已经尝试过了

There can be many ways, one ways is using $lookup as you already tried

db.place.aggregate([
  { "$match": { "place": "Room 5" } },
  { $unwind: "$type_place_objects"  },
  {
    "$lookup": {
      "from": "type_place",
      "let": { tpo: "$type_place_objects._id" },
      "pipeline": [
        { $unwind: "$objects" },
        {
          $match: {
            $expr: {
              $eq: [ "$objects._id", "$$tpo" ]
            }
          }
        }
      ],
      "as": "join"
    }
  },
  {
    $addFields: {
      "join": { "$arrayElemAt": [ "$join", 0]
      }
    }
  },
  {
    $addFields: { "type_place_objects.name": "$join.objects.name" }
  },
  {
    $group: {
      _id: "$_id",
      place: { $first: "$place" },
      type_place_objects: { "$addToSet": "$type_place_objects" }
    }
  }
])

工作 Mongo 游乐场

这篇关于如何调用子数组中另一个集合中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 17:04