mongodbmongodb-querymongo-java

Find objects by array in mongodb (or java)


I've got a collection (dataset) like this:

{
  "_id" : ObjectId("515611c1c6e3718ee42a5655"),
  "id": "Product1",
  "type": "ProductType4"
  "productFeature": [
    {
      "id": "ProductFeature1"
    },
    {
      "id": "ProductFeature2"
    },
    {
      "id": "ProductFeature3"
    }
  ]
  "productPropertyNumeric": 25
},     
... and more product objects...

{
  "_id" : ObjectId("515611c1c6e3718ee42a5666"),
  "id": "ProductFeature1",
  "label": "blablabla" 
},
{
  "_id" : ObjectId("515611c1c6e3718ee42a5667"),
  "id": "ProductFeature2",
  "label": "blebleble" 
},
{
  "_id" : ObjectId("515611c1c6e3718ee42a5668"),
  "id": "ProductFeature3",
  "label": "blublublu" 
}      ... and more feature objects...

According to Product1, I have to find the features and labels that the specific product has in its "productFeature" array.

I have tried in Mongo shell to find them (using a variable, for example):

var aaa = db.dataset.find({ id: "Product1" })

db.dataset.find({ id: "aaa.productFeature.id" })

But it doesn't work. If somebody knows how to find objects by array please help me. Thanks very much.

PS: It would be best in Java - I apply a query just for example:

    BasicDBObject query = new BasicDBObject();

    query.put("type","ProductType4");
    query.put("productPropertyNumeric", new BasicDBObject("$gt", 10));

    DBCursor cursor = coll.find(query).sort( new BasicDBObject("label", 1));
    while (cursor.hasNext()){
       System.out.println(cursor.next().get("id"));  
} 

Solution

  • Here is my answer to my own question. I hope this helps to someone.

    BasicDBObject query = new BasicDBObject();
        BasicDBObject field = new BasicDBObject();
    
        query.put("id", "Product1");
        field.put("id", 1);
        field.put("productFeature", 1);      
        field.put("_id", 0);
    
        DBCursor cursor = coll.find(query, field);
        while (cursor.hasNext()) {
            BasicDBObject result = (BasicDBObject) cursor.next();
            System.out.println(result);
            ArrayList<BasicDBObject> features = (ArrayList<BasicDBObject>) result.get("productFeature");
    
            for (BasicDBObject embedded : features) {
                String featuresId = (String) embedded.get("id");
    
                BasicDBObject query2 = new BasicDBObject();
                BasicDBObject field2 = new BasicDBObject();
    
                query2.put("id", featuresId);
                field2.put("id", 1);
                field2.put("label", 1);
                field2.put("_id", 0);
                DBCursor cursor2 = coll.find(query2, field2);
    
                while (cursor2.hasNext()) {
                    System.out.println(cursor2.next());
                }
            }
        }