Lin Shen
Lin Shen

Reputation: 595

Find documents base on a computed value from an array of object in mongoDB

I'm new to MongoDB, and I would like to know how can I find documents base on a "computed value" from an array of objects.

For example, let's say the computed text is the concatenation of all the text under "transcript .data".

If a user searches "hello", I want to return both documents, and if a user searches "hello world", I want to return the first document.

[{
  "_id": ...
  "transcript": {
    "data": [
      {
        "text": "hello "
      },
      {
        "text": "world"
      }
    ],
  }
},{
  "_id": ...
  "transcript": {
    "data": [{
        text: "hello"
     }],
  }
}]

I'm using MongoDB 3.6.3 in the node.js environment. So I can't use $expr with $function. Moreover, the $where operation doesn't work for me neither as pointed out in this question.

I would be grateful if anyone could help!

Upvotes: 1

Views: 99

Answers (1)

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5689

i believe you can achieve your goal with an aggregation pipeline like this:

var input = "hello world".split(' ');

db.collection.aggregate(
[
    {
        $match: {
            $expr: {
                $setIsSubset: [
                    input,
                    {
                        $map: {
                            input: "$transcript.data",
                            as: "t",
                            in: { $trim: { input: "$$t.text" } }
                        }
                    }
                ]
            }
        }
    }
])

but you do have to supply the input phrase as an array of strings to mongodb.

https://mongoplayground.net/p/FlUDLfMvuIa

Upvotes: 1

Related Questions