2

I am working on a project with Spring Integration. At some point in the message flow I am using a MongoDB Outbound Channel Adapter to save the payloads into my mongodb database.

Is there a way that I can immediately get the id of the documents as they get inserted? Basically, just after insertion of a document I need its id to be passed on to another channel for further processing. What is the best approach to achieve this leveraging the Spring Integration infrastructure?

Tanvir
  • 542
  • 7
  • 16
  • @Neil Lunn This is not a duplicate question. This question is specific to Spring Integration and not intended for a java-based solution which is the focus of the other thread. Please see my comment against https://stackoverflow.com/a/29471597/2012594 – Tanvir Nov 26 '18 at 01:11
  • The answers provided are an exact duplicate of the answers on the linked question. That makes it a duplicate. – Neil Lunn Nov 26 '18 at 01:13

2 Answers2

4

From MongoTemplate.insert(Object):

If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See Spring's Type Conversion" for more details.

Andrei Sfat
  • 8,440
  • 5
  • 49
  • 69
  • Thank you sfat. The approach you shown is the spring-data way of doing it. However, I have been looking for a solution using features found in Spring Integration (if any). For example, (as I mentioned in my question) I can save payloads to my database without directly using any mongo-java or spring-data API. It would be great if I could find a similar way to get the inserted document id. Still I have upvoted your answer as it partially solves my problem. Much appreciated. – Tanvir Apr 06 '15 at 23:26
  • @Tanvir have you looked over this guy? http://stackoverflow.com/questions/21459319/spring-integration-messagechannel-id It seems to be something you want, if you wanna make use Spring Integration – Andrei Sfat Apr 07 '15 at 07:30
2

You could try:

BasicDBObject doc = new BasicDBObject("foo", "bar");
collection.insert(doc);
ObjectId id = (ObjectId)doc.get("_id");
chridam
  • 100,957
  • 23
  • 236
  • 235
  • Thank you chridam. The approach you shown is the java way of doing it using mongo-java-driver. However, I have been looking for a solution using features found in Spring Integration (if any). Still I have upvoted your answer as it partially solves my problem. – Tanvir Apr 06 '15 at 23:26