0

what I tried to is getting all sitename from every embedded documents in the array.I have tried using following syntax but didn't work

( sites.$.site )

{
  "user" : "username",
  "sites" : [{
      "sitename" : "site.com",
      "url" : "site.com",
      }, {
      "sitename" : "site2.com",
      "url" : "site2.com",
      },{
      "sitename" : "site2.com",
      "url" : "site2.com",
   }]
}
Amal Madawa
  • 187
  • 1
  • 14
  • "sites.$.site" seems to be a typo. Surely "sites.sitename" ? – Vince Bowdren Mar 10 '17 at 09:19
  • Possible duplicate of [Search by element of an object in a array](http://stackoverflow.com/questions/22343650/search-by-element-of-an-object-in-a-array) – Vince Bowdren Mar 10 '17 at 09:22
  • I want to list all sitenames. – Amal Madawa Mar 10 '17 at 09:40
  • Possible duplicate of [Finding distinct from collections in mongodb](http://stackoverflow.com/questions/40246302/finding-distinct-from-collections-in-mongodb). Use "sites.sitename" as name key in linked answer for your case. – s7vr Mar 10 '17 at 10:36

1 Answers1

1

Mongo-java,

        MongoClient mongoClient = new MongoClient("localhost",27017);
        MongoDatabase database = mongoClient.getDatabase("Test");

        MongoCollection<Document> collection = database.getCollection("collection");
        ArrayList<Document> doc = new ArrayList<Document>();
        doc.add(new Document().append("$unwind","$sites"));
        doc.add(new Document().append("$project",new Document().append("sitename","$sites.sitename")));
        List<Document> results =collection.aggregate(doc).into(new ArrayList<Document>());
        for(Document res: results){
            System.out.println(res.toJson());
        }

output:

        { "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site.com" }
        { "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site2.com" }
        { "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site2.com" }
radhakrishnan
  • 1,399
  • 1
  • 14
  • 20
  • why do u use Document Instead of BasicDbObject ? i used BasicDbObject and did some changes. but it works thanks – Amal Madawa Mar 10 '17 at 10:53
  • from mongodb3.0 onwards MongoCollection insert ,update, qurery ,aggregate and most of methods accept only org.bson.Document – radhakrishnan Mar 10 '17 at 11:13