0

How do I create a view in mongo db which can expose all the documents from a collection? I have used following code:

java.util.List<Bson> tstL = new ArrayList<>();
db.createView("tst_view","collection_name",tstL);

I am trying it with empty list for pipeline but it doesn't work. Can you please help?

glytching
  • 44,936
  • 9
  • 114
  • 120
passionate
  • 503
  • 2
  • 7
  • 25
  • Can you be specific about what "it doesn't work" means? Does the `createView` method throw an exception? Does the `createView` method complete successfully but when you try to use the view, the view does not exist? The more detail you provide the greater the chance that someone will be able to help you. – glytching Jan 02 '18 at 11:54
  • Perhaps the 'issue' is that the view doesn't seem to exist in the target database? If so, then that's because views are computed on demand during read operations. Views are not materialised like collections are, instead the target database will contain a document in `system.views` defining your view and you'll be able to use this view - via the Mongo Java driver - in much the same way as you use a collection. – glytching Jan 02 '18 at 15:02
  • createView fails because I can't use empty list as pipeline. But I don't understand what the pipeline should be if I don't want to filter on any condition. I just want to expose all the data from collection in the view. – passionate Jan 02 '18 at 15:50
  • I can successfully invoke `createView("a", "b", new ArrayList<>())` using mongodb-driver-3.5.0.jar. Can you be specific about what "fails" means; does the driver throw an exception? If so, can you update your question to include the stacktrace? – glytching Jan 02 '18 at 16:06
  • Thank you. It worked. I had timeout issue earlier. When I went to logs in one of the nodes, I could see that it has timeout in connecting to mongodb. – passionate Jan 04 '18 at 19:18

1 Answers1

0
    database.createView("Tree", "Node", asList(
            new Document("$graphLookup",
                    new Document("from", "Node")
                            .append("startWith", "$childrenRefs")
                            .append("connectFromField", "childrenRefs")
                            .append("connectToField", "_id")
                            .append("as", "children")
            )
    ));
Sam
  • 899
  • 6
  • 9