3

I have a document -

  {"_id" : ObjectId("51385d2308d427ce306f0100"),
  "aid" : "1",
  "studyId" : "study-1",
  "mediaType" : "microBlog",
  "text" : "bla bla",
  "sentences" : "bla bla",
  "status" : {
          "algo1" : "required",
          "algo2" : "required",
          "algo3" : "completed",
          "algo4" : "completed"
  },
  "priority" : "u"}

The status field has multiple sub-fields with different status values. Is it possible to create a query such that it returns all documents for which any of the status sub-field's value is "required"?

Something like db.foo.find({status : "required"}) which would give me all documents for which any of the sub-field has value "required"

3 Answers 3

5

Another, more efficient, approach would be to implement your "status" sub-document as an array of "typed values", like this:

 {"_id" : ObjectId("51385d2308d427ce306f0100"),
  "aid" : "1",
  "studyId" : "study-1",
  "mediaType" : "microBlog",
  "text" : "bla bla",
  "sentences" : "bla bla",
  "status" : [
          { type: "algo1", value: "required" },
          { type: "algo2", value: "required" },
          { type: "algo3", value: "completed" },
          { type: "algo4", value: "completed" }
  ],
  "priority" : "u"}

This would allow you to find all the documents, for which any of the sub-field has value "required", with this query:

db.foo.find({"status.value":"required"})

Defining an index on this sub-field would speed up the query:

db.foo.ensureIndex({"status.value":1})
Sign up to request clarification or add additional context in comments.

Comments

0

u could search via db.foo.find({ 'status.algo1' : 'required' }) or db.foo.find({ 'status.algo2' : 'required' }), but it's probably not possible to filter by regex keys, see also this post: https://stackoverflow.com/a/7290728/654952

1 Comment

Yes, I would need to use or conditions for each status.algo as what I require is not possible in Mongo.
0

you could use mapReduce() where the map() function would contain something like:

// loop all key/value pairs in status without knowing its key
for ( item in this.status ) {
    // if value is required: emit the data and break the loop
    if ( this.status[item] == "required" ) {
        emit( ... )
        break;
    }
}

does this help ?

Cheers

Ronald

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.