Mongo Query on Subfields

后端 未结 3 1401
情书的邮戳
情书的邮戳 2021-01-06 15:59

I have a document -

  {\"_id\" : ObjectId(\"51385d2308d427ce306f0100\"),
  \"aid\" : \"1\",
  \"studyId\" : \"study-1\",
  \"mediaType\" : \"mic         


        
相关标签:
3条回答
  • 2021-01-06 16:27

    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

    0 讨论(0)
  • 2021-01-06 16:30

    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

    0 讨论(0)
  • 2021-01-06 16:35

    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})
    
    0 讨论(0)
提交回复
热议问题