0

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

2
  • 3
    With such schema where you have hash keys it would be pretty difficult to query unless you can change it so that the dynamic book ids are embedded in an array. Commented Apr 11, 2016 at 13:28
  • You actually want a structure like "books": [{ "_id": "570a385737000012009e6f65", "title": "a1", "status": "published" },{..}] Which then makes for simple queties like { "books.status": "pending" }. Point is that named keys need an "explicit" path, but without them the name of the "path" is the same for all elements. Commented Apr 12, 2016 at 1:13

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

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.