开发者

Mongo mapper (Mongo DB) embedded document multiple field searching

开发者 https://www.devze.com 2023-03-30 19:10 出处:网络
\"user_crawls\": { \"0\": { \"_id\": ObjectId(\"4e4b5e1c151c0d0336000093\"), \"rand_id\": \"kPxMuXOY8Jfh6nXt\",
 "user_crawls": {
     "0": {
       "_id": ObjectId("4e4b5e1c151c0d0336000093"),
       "rand_id": "kPxMuXOY8Jfh6nXt",
   开发者_运维问答    "network": "tw",
       "sourcenetwork": "874777",
       "sourceName": "Krishna",
    },
     "1": {
       "_id": ObjectId("4e4b5e1c151c0d0336000094"),
       "rand_id": "kPxMuXOY8Jfh6nXt",
       "network": "fb",
       "sourcenetwork": "145875",
       "sourceName": "Krishna",
    },
  "2": {
       "_id": ObjectId("4e4b5e1c151c0d0336000095"),
       "rand_id": "kPxMuXOY8Jfh6nXt",
       "network": "fb",
       "sourcenetwork": "145875",
       "sourceName": "Ram",
    }

I want to select the docs whose network is fb and sourcename is Krishna. From the abouve data normally i would like to get the result the second doc whose id is

4e4b5e1c151c0d0336000094

But I am getting all records

I used the following code to collect the data

DdNetworkCrawlLink.limit(10).all(:conditions => {'user_crawls.network' => "fb",'user_crawls.sourceName' => "Krishna")

Thanks For your time

Sreeraj


When querying in Mongo you can only query for root documents. So it also is in MongoMapper.

To get just the embedded documents that match, you have to query for all the root documents first, then pull the embedded documents out of them:

DdNetworkCrawlLink
.limit(10)
.all('user_crawls.network' => "fb",'user_crawls.sourceName' => "Krishna")
.map do |dbncl|
  dcncl.user_crawls.select { |uc| uc.network == "fb" && uc.sourceName == "Krishna" }
end.flatten

Because the above code is so convoluted, it's recommend to only embed documents when the embedded documents will always be used/displayed/needed at the same time as their parent.


i think you missed ':' char. at documentation on mongomapper it says

Patient.all(:last_name => 'Johnson', :order => :last_name.asc)
0

精彩评论

暂无评论...
验证码 换一张
取 消