1

In Mongodb if I have a structure like below, and I know the string let's say at vid > 0 > 0 how can I get the whole vid > 0 array returned? So that I can access also vid > 0 > 1 and vid > 0 > 2 ?

enter image description here

EDIT: db document structure:

...
updatedAt: 2021-01-17T16:44:28.824+00:00
vid: (Array)
  0: (Array)
    0: "adfsdfasfd"
    1: "this is some sample text"
    2: "https://example.com"
  1: (Array)
    0: "gfjghjhjgh"
    1: "this is another sample text"
    2: "https://example2.com"
...

So the question in regard to the text example above this time, is how do I get the whole Array 0 if I know the "adfsdfasfd" string?

1
  • just provide a sample document in text content instead of screenshot. Commented Jan 17, 2021 at 17:15

1 Answer 1

2

Using aggregation query:

  • $match condition, put nested $ememMatch for 2 level condition
  • $reduce to iterate loop of vid array, set initial [], check condition if string in current array then return current array otherwise return initial value
let searchString = "adfsdfasfd";
db.collection.aggregate([
  {
    $match: {
      vid: { $elemMatch: { $elemMatch: { $in: [searchString] } } }
    }
  },
  {
    $addFields: {
      vid: {
        $reduce: {
          input: "$vid",
          initialValue: [],
          in: {
            $cond: [{ $in: [searchString, "$$this"] }, "$$this", "$$value"]
          }
        }
      }
    }
  }
])

Playground

Result:

[
  {
    "vid": [
      "adfsdfasfd",
      "this is some sample text",
      "https://example.com"
    ]
  }
]

Using find query:

  • Put match condition same as above
  • for projection get match result but in same nested array
let searchString = "adfsdfasfd";
db.collection.find(
  { vid: { $elemMatch: { $elemMatch: { $in: [searchString] } } } }
).project({ "vid.$": 1, _id: 0 }).toArray()

Playground

Result:

[
  {
    "vid": [
      [
        "adfsdfasfd",
        "this is some sample text",
        "https://example.com"
      ]
    ]
  }
]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I'm testing this out, the find query option, given that we have to add ".toArray()" at the end, returns the whole document instead of the array 0 . same for the aggregate option
I think that's because the playground you used to test uses an old version of mongodb or viceversa, in my case using ".project({ "vid.$": 1, "_id": 0 }).toArray()" to filter worked! if you modify your answer i'll mark it as the solution

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.