Reputation: 955
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
?
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
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 valuelet searchString = "adfsdfasfd";
db.collection.aggregate([
{
$match: {
vid: { $elemMatch: { $elemMatch: { $in: [searchString] } } }
}
},
{
$addFields: {
vid: {
$reduce: {
input: "$vid",
initialValue: [],
in: {
$cond: [{ $in: [searchString, "$$this"] }, "$$this", "$$value"]
}
}
}
}
}
])
Result:
[
{
"vid": [
"adfsdfasfd",
"this is some sample text",
"https://example.com"
]
}
]
Using find query:
let searchString = "adfsdfasfd";
db.collection.find(
{ vid: { $elemMatch: { $elemMatch: { $in: [searchString] } } } }
).project({ "vid.$": 1, _id: 0 }).toArray()
Result:
[
{
"vid": [
[
"adfsdfasfd",
"this is some sample text",
"https://example.com"
]
]
}
]
Upvotes: 2