Home > Blockchain >  is there any mongo db query to fetch all the nested elements
is there any mongo db query to fetch all the nested elements

Time:01-23

my data structure is

[
  {
    "item": "journal",
    "qty": 25,
    "status": "A",
    "products": [
        {
            "key": "item-one",
            "name": "item one",
            "tags": ["a", "b"]
        },
        {
            "key": "item-two",
            "name": "item-two",
            "tags": ["a", "c", "d"]
        },
        {
            "_id": 3,
            "name": "item-three",
            "tags": ["g"]
        }
    ]
  },
  {
    "item": "notebook",
    "qty": 50,
    "status": "b",
    "products": [
        {
            "key": "item-four",
            "name": "item four",
            "tags": ["a", "o"]
        },
        {
            "key": "item-five",
            "name": "item-five",
            "tags": ["s", "a", "d"]
        }
    ]
  }
]

and I want to find all the elements with tags a, so the expected response should be like

[
  {
    "item": "journal",
    "qty": 25,
    "status": "A",
    "products": [
        {
            "key": "item-one",
            "name": "item one",
            "tags": ["a", "b"]
        },
        {
            "key": "item-two",
            "name": "item-two",
            "tags": ["a", "c", "d"]
        },
    ]
  },
  {
    "item": "notebook",
    "qty": 50,
    "status": "b",
    "products": [
        {
            "key": "item-four",
            "name": "item four",
            "tags": ["a", "o"]
        },
        {
            "key": "item-five",
            "name": "item-five",
            "tags": ["s", "a", "d"]
        }
    ]
  }
]

CodePudding user response:

You can use the $filter operator to filter the element containing "a" in the tags array for the products array in the projection.

db.collection.find({
  "products.tags": "a"
},
{
  item: 1,
  qty: 1,
  status: 1,
  products: {
    $filter: {
      input: "$products",
      cond: {
        $in: [
          "a",
          "$$this.tags"
        ]
      }
    }
  }
})

Demo @ Mongo Playground

  • Related