2

I have data stored in following format in mongodb .. help me in knowing how can I write a query to find if the database has a particular id stored in one of the sheet or not

the structure of data is like the following :-

{
    "name": "abc",
    "linked_data": {
      "sheet 1": [
        "7d387e05d3f8180a",
        "8534sfjog904395"
      ],
      "sheet 2": [
        "7d387e05d3f8180a",
        "54647sgdsevey67r34"
      ]
    }
  }

for example if id "8534sfjog904395" is mapped with "sheet 1".. then it should return me this data where id is mapped with the sheet. I am passing id in the query and want to find inside linked_data and then all the sheets

1 Answer 1

1

Using dynamic value as field name is considered as an anti-pattern and introduce unnecessary complexity to queries. Nevertheless, you can use $objectToArray to convert the linked_data into array of k-v tuples. $filter to get only the sheet you want. Finally, revert back to original structure using $arrayToObject

db.collection.aggregate([
  {
    "$set": {
      "linked_data": {
        "$objectToArray": "$linked_data"
      }
    }
  },
  {
    $set: {
      linked_data: {
        "$filter": {
          "input": "$linked_data",
          "as": "ld",
          "cond": {
            "$in": [
              "8534sfjog904395",
              "$$ld.v"
            ]
          }
        }
      }
    }
  },
  {
    "$set": {
      "linked_data": {
        "$arrayToObject": "$linked_data"
      }
    }
  },
  {
    $match: {
      linked_data: {
        $ne: {}
      }
    }
  }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

2 Comments

can't we acheive this without aggregate? by using find ?
@PrityPriya unlikely. You probably will end up getting the raw document(i.e. without array entries filtered). And that likely will impact the readability much as it packs all the code together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.