0

I have one document like this:

-document: users-
{
"name": "x", password: "x" recipes: 
[{title: eggs, dificult: 1},{title: "pizza" dificult: 2}],
name: "y", password: "y" recipes: [{title: "oil", dificult: 2},{title: "eggandpotatoes" dificult: 2}]
}

I want to get all recipes filtering by title and dificult

I have tried some like this

db.users.find({$and: [{"recipes.title": /.*egg.*/},{"recipes.dificult": 2}]}, 
{"recipes.title": 1,"recipes.dificult": 1}).toArray();

this should return

{title: "eggandpotatoes" dificult: 2}

but return

{title: eggs, dificult: 1}
{title: "eggandpotatoes" dificult: 2}

I would like once the filter works, limit the result with start: 2 and end: 5 returning from the 2 result the next 5.

Thanks in advance.

2 Answers 2

1

You can use the $filter aggregation to filter the recipes and $slice to limit the results. It will give you everything you are looking expect but regex search which is not possible as of now.

db.users.aggregate([{
    $project: {
        _id: 0,
        recipes: {
            $slice: [{
                $filter: {
                    input: "$recipes",
                    as: "recipe",
                    "cond": {
                        $and: [{
                            $eq: ["$$recipe.title", "eggandpotatoes"]
                        }, {
                            $eq: ["$$recipe.dificult", 2]
                        }]
                    }
                }
            }, 2, 3]
        }
    }
}]);
Sign up to request clarification or add additional context in comments.

Comments

0

If you need to find out regular expression in title then use $elemMatch as below :

db.users.find({"recipes":{"$elemMatch":{"title": /.*egg.*/,"dificult": 2}}}, {"recipes.$":1})

One thing I mentioned here if your recipes array contains some thing like this

"recipes" : [ { "title" : "egg", "dificult" : 2 }, { "title" : "eggand", "dificult" : 2 } ]

then $ projection return only first matched array objcect in above case it will be

"recipes" : [ { "title" : "egg", "dificult" : 2 } ]

If you need this both array then go to @Sagar answer using aggregation

Comments

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.