m4tt
m4tt

Reputation: 955

Get whole array by one of its strings. Array is inside another array. Mongodb/Javascript

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?

Upvotes: 1

Views: 57

Answers (1)

turivishal
turivishal

Reputation: 36114

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"
      ]
    ]
  }
]

Upvotes: 2

Related Questions