Lucke
Lucke

Reputation: 316

MongoDB filter inner array of object

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.

Upvotes: 0

Views: 4577

Answers (2)

Neo-coder
Neo-coder

Reputation: 7840

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

Upvotes: 0

s7vr
s7vr

Reputation: 75984

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]
        }
    }
}]);

Upvotes: 1

Related Questions