0

I have a MongoDB collection called references that has a document where I need to return all the objects that have a key called format with the value of 1. An example of the document looks like this:

{
    "_id" : ObjectId("878f92ad6d9e8089aa3456a9"),
    "categories" : {
            "1" : {
                    "format" : 1,
                    ...
            }
    }
}

I have tried this:

db.references.find({
    "_id" :  ObjectId("878f92ad6d9e8089aa3456a9"), 
    "categories.$.format" : 1
}).pretty();

As well as this:

db.references.find({
    "_id" :  ObjectId("878f92ad6d9e8089aa3456a9"), 
    "categories.*.format" : 1
}).pretty();

and both of those are returning nothing.

2 Answers 2

2

I think schema design is not quite well. Having a schema design like the following:

{
    "_id" : ObjectId("57fbe76f78c1638eaebfb21f"),
    "categories" : [
        {
            "cat_name" : 1,
            "format" : 1
        },
        {
            "cat_name" : 2,
            "format" : 6
        }
    ]
}

Makes much more sense, this way you can access the format field of the embedded category documents simply using dot notation. The query you requested can be: db.stackQuestion.find({ "categories.format": 1 })

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

1 Comment

I agree the structure needed an update so I went that direction. Thanks for the suggestions!
-1

The mongoDB enables checking the existance of a field in the document by using the $exists element query operator.

The using of the property _id means that you want to extract specific document from the collection when you know its id so it can return at most 1 object. That is why you should not use the following line inside the query:

"_id" : ObjectId("878f92ad6d9e8089aa3456a9")

Simple query to get all the documents contains the categories field should look like this:

db.references.findAll( { 
  categories: { $exists: true } 
}).pretty();

By using the following query you get in one query all the results you wish to get:

db.references.find({ categories: { $exists:true }, 
                    "categories.$" : { $elemMatch: { "format": "1" } } 
}).pretty();

The $ is used for deep search for any element under categories.

For more information please read : $match , element match,

1 Comment

Unfortunately $elemMatch only works on arrays, not on documents. So this does not answer the original question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.