Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose find document by key whose value is a complex object

I am using Mongoose to do a search for documents in a collection based on the criteria described below:

Document:

{
    "_id": {
        "$oid": "5a60621e20205641281f7c2f"
    },
    "key1": [
        {
            "available": true,
            "required": true,
            "name": "Name-1"
        },
        {
            "available": true,
            "required": true,
            "name": "Name-2"
        },
        {
            "available": true,
            "required": true,
            "name": "Name-3"
        }
    ],
    "__v": 0
}

I want to perform a search based on property key1. So basically what I want to do is pass the json object as search pattern below and get the result as the document above in return

[
        {
            "available": true,
            "required": true,
            "name": "Name-1"
        },
        {
            "available": true,
            "required": true,
            "name": "Name-2"
        },
        {
            "available": true,
            "required": true,
            "name": "Name-3"
        }
    ]

Is there a way that I can achieve this?

like image 778
Brijesh Prasad Avatar asked Jan 18 '18 17:01

Brijesh Prasad


1 Answers

You can check $eq in mongodb docs $eq.

const selector = [
    {
        "available": true,
        "required": true,
        "name": "Name-1"
    },
    {
        "available": true,
        "required": true,
        "name": "Name-2"
    },
    {
        "available": true,
        "required": true,
        "name": "Name-3"
    }
];

Model.find({key1: {$eq: selector}}, (error, result) => {
    if(!err) {
    res.send(result);
    }
});

Model is the collection you fetch from.

like image 134
Tarek Essam Avatar answered Sep 27 '22 21:09

Tarek Essam