简体   繁体   中英

MongoDB: How to find (and return) elements in a multidimensional array?

This is the JSON structure, note that the last entry has 2 multidimensional arrays in it, one for chr 10 and one for chr 12:

{
  "_id": "9oFvJYeG9wpdBYunu",
  "segments": [
    {
      "chr": "7",
      "start": "140422294",
      "end": "155048283",
      "length": "29.1",
      "snps": "1666"
    }
  ]
},
{
  "_id": "HK4WXc5mR6fyesjpP",
  "segments": [
    {
      "chr": "10",
      "start": "83865742",
      "end": "90981118",
      "length": "6.3",
      "snps": "1380"
    }
  ]
},
{
  "_id": "3N4Z2dtX5PiuqmCFv",
  "segments": [
    {
      "chr": "10",
      "start": "83865742",
      "end": "90981118",
      "length": "6.3",
      "snps": "1380"
    },
    {
      "chr": "12",
      "start": "32853998",
      "end": "44834540",
      "length": "5.1",
      "snps": "1623"
    }
  ]
}

How can I identify all segments with chr = 10? I want to get the detailed information about the elements with chr = 10. I want exactly those elements with chr = 10, not give me all documents (with all other their segments) where one of the elements has chr = 10.

Please further note that according to the MongoDB documentation both '$elemMatch' and '$' only return the first match. However my collection has documents where there are two or more elements with chr = 10. I want to get all elements, also in this case with multiple chr 10 elements in one array.

I want to return the following fields:

_id, chr, start, end, length, snps

back. How can I query this in Meteor? I tried $elemMatch an $in but to no avail. If you only answer this for MongoDB please do so, I will try to convert it into Meteor Javascript.

Thanks in advance for your help!

PS: this is on the Meteor server side, not sure if that's important

you can try find with projection

Query

db.collection.find({"segments.chr":"10"},{"segments.$":1}).pretty()

Output

{
        "_id" : "HK4WXc5mR6fyesjpP",
        "segments" : [
                {
                        "chr" : "10",
                        "start" : "83865742",
                        "end" : "90981118",
                        "length" : "6.3",
                        "snps" : "1380"
                }
        ]
}
{
        "_id" : "3N4Z2dtX5PiuqmCFv",
        "segments" : [
                {
                        "chr" : "10",
                        "start" : "83865742",
                        "end" : "90981118",
                        "length" : "6.3",
                        "snps" : "1380"
                }
        ]
}

Hope it will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM