1

I store in mongodb some documents that have the following structure:

{
"a":1,
"b":24.212,
"uup":"X243",
"fvp": [
  {
    "feature_id": 10,
    "value": 180.157,
    "units": "A"
  },
  {
    "feature_id": 83,
    "value": 180.042252,
    "units": "mP",
  },
  {
    "feature_id": 62,
    "value": 0.234,
    "units": ""   
  }
]
} 

and in general I may have some tens or even hundreds of elements inside array fvp. I want to perform a search as follows:

db.colX.find({"_id" : ObjectId("54b44b3bfeee5a13a43f34f0")});

but get just the elements in fvp whose feature_id is in a range of values. For example, I would like to get the following result:

{ "a":1, "b":24.212, "uup":"X243", "fvp": [ { "feature_id": 10, "value": 180.157, "units": "A" }, { "feature_id": 62, "value": 0.234, "units": ""
} }

specifying that I want to get only the element of fvp with "feature_id":10 OR "feature_id":62 . Is this anyhow possible? It seems that this can be done when just a single feature_id is specified, using the keyword $elemMatch. Here is an example:

db.colX.find(
  {"_id" : ObjectId("54b44b3bfeee5a13a43f34f0")},
  {
    feature_value_pairs: 
      {$elemMatch: {feature_id: 10} }
  }
);

Question #1: This suppresses other fields of my document from being displayed (e.g., a, b, uup). Can this be avoided?

Things get more complicated when I want to specify that I want the retrieved document to have the elements with feature_id equal to 10 and 83 together. Here is what I tried:

db.colX.find(
  {"_id" : ObjectId("54b44b3bfeee5a13a43f34f0")},
  {
    feature_value_pairs: 
     {$elemMatch: {feature_id: { $in: [10, 83]}} }
  }
);

However this displays just the element with feature_id:10.

Question #2: How can I achieve the desired result in mongodb?

Pantelis Sopasakis
  • 1,837
  • 4
  • 25
  • 44
  • @NeilLunn I updated my question. I read http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection and it didn't help me find a solution to my problem. – Pantelis Sopasakis Jan 13 '15 at 00:42
  • 1
    `$elemMatch` in projection is just one of the possible answers. There are many answers on that question, so not just the accepted one is correct. For multiple matches use `.aggregate()` as explained in several answers there. – Neil Lunn Jan 13 '15 at 00:49

0 Answers0