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",
   }]
}
4
  • "sites.$.site" seems to be a typo. Surely "sites.sitename" ? Commented Mar 10, 2017 at 9:19
  • Possible duplicate of Search by element of an object in a array Commented Mar 10, 2017 at 9:22
  • I want to list all sitenames. Commented Mar 10, 2017 at 9:40
  • Possible duplicate of Finding distinct from collections in mongodb. Use "sites.sitename" as name key in linked answer for your case. Commented Mar 10, 2017 at 10:36

1 Answer 1

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" }
Sign up to request clarification or add additional context in comments.

2 Comments

why do u use Document Instead of BasicDbObject ? i used BasicDbObject and did some changes. but it works thanks
from mongodb3.0 onwards MongoCollection insert ,update, qurery ,aggregate and most of methods accept only org.bson.Document

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.