Reputation: 105
I am not sure how I am going to solve this problem:
I want to search in a mongoDB collection and return only the nested objects that fits the search query (using text search on all of the fields).
All documents in the collection have this format:
{
arr: [
{
_id: 1,
name: 'Random',
description: 'Hello world'
},
{
_id: 2,
name: 'World',
description: 'This is a random description'
},
{
_id: 3,
name: 'Random',
description: 'Hi'
}
]
}
In this case, if my search query is 'world', then this should be the result:
[
{
_id: 1,
name: 'Random',
description: 'Hello world'
},
{
_id: 2,
name: 'World',
description: 'This is a random description'
},
//... objects from other documents in the collection that fits the query
]
If this is not possible in mongoDB, are there any JavaScript libraries that can achieve this? Would greatly appreciate the help!
Upvotes: 4
Views: 1505
Reputation: 35408
With the aggregation framework it could look like so
db.getCollection('yourCollection').aggregate([
{
$unwind: '$arr'
},
{
$match: {
$or: [
{ 'arr.name': /world/i },
{ 'arr.description': /world/i }
]
}
},
{
$project: {
_id: '$arr._id',
name: '$arr.name',
description: '$arr.description'
}
}
])
which will result in the following output for your example data:
{
"_id" : 1,
"name" : "Random",
"description" : "Hello world"
}
{
"_id" : 2,
"name" : "World",
"description" : "This is a random description"
}
If you have the need for a single array with the resulting documents as shown in your question, you can simply chain a toArray()
call at the end of the pipeline - keep in mind though that this may cause increased memory consumption in case of large result sets as pointed out by SSDMS in the comments.
Upvotes: 3