igx
igx

Reputation: 4231

Search element in indexed array

I am newbie with MongoDb I have a document with this structure :

{
    "_id": "570a38612959856808fe9b1d",
    "author": "foo",
    "books": {
        "570a385737000012009e6f65": {
            "title": "a1",
            "status": "published"
        },
        "570a385737000012009e6f66": {
            "title": "a2",
            "status": "pending"
        },
        "570a385737000012009e6f67": {
            "title": "a1",
            "status": "published"
        }
    }
}

how can I search for all authors that have pending books ? I tried something like

{ "books":{$elemMatch:{"status": "pending" }}}

but got nothing

Upvotes: 0

Views: 35

Answers (1)

markwatsonatx
markwatsonatx

Reputation: 3501

I agree with the comments that this is not the ideal structure for your data, but it is possible to query for all authors who have pending books using the $where operator. The $where operator takes a Javascript function:

db.authors.find({"$where" : function() {
    if (this.books) {
        for (var i in this.books) {
            if (this.books[i].status == 'pending') {
                return true;
            }
        }
    }
    return false;
}});

...or a Javascript expression (essentially the contents of the function as a string):

db.authors.find({"$where" : "if (this.books) { for (var i in this.books) { if (this.books[i].status == 'pending') { return true; }}} return false;"});

You can still specify which fields to return, etc.

db.authors.find({"$where" : function() {
    ...
}},{author:1});

More information on the $where operator:

https://docs.mongodb.org/manual/reference/operator/query/where/

Upvotes: 1

Related Questions