4

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!

1 Answer 1

3

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.

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

4 Comments

Why to you need toArray() here?
To exactly match his desired result
toArray() loads all the documents into RAM. what is it useful for here? NOTHING
I agree that toArray() is usually not necessary but wanted to match the result to be as close to the desired result as possible - which admittedly is wrong in this case as users may think one absolutely has to use it. I updated the answer accordingly and hope we got a suitable compromise :)

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.