1

I have the following object:

{ 
   "id" : "sampleId";
   foos : [{
         "prop1":"value1",
         "prop2":"value2"
      },
      {
         "prop1":"value3", 
         "prop2":"value4"
      }
]}

How can I get foos, where prop2 is value4? I'm using Spring data mongodb.

2 Answers 2

1

If you use spring data mongodb repositories, it can make your life easy. You will need a domain class. e.g.

public class Foo {
    String prop1;
    String prop2;
}

public class MyClass {
    String id;
    List<Foo> foos;
}

public interface MyClassRepository extends MongoRepository<MyClass, String> {
    List<MyClass> findByFoosProp2(String prop2ValueToLookFor);
    // assuming you can find multiple matches
}

Then simply call this method from your code

public clsss SomeBusinessClass {
    @Autowired
    private MyClassRepository repository;

    public void mySomeBusinessMethod() {
        List<MyClass> myObjects = repository.findByFoosProp2("value4");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

This code will return a SampleBean with id sampleId wich will have only matching items in collection foos.

// Match one document with sampleId
Query q1 = new Query(where("id").is("sampleId"));

// match only foos with prop2 value value2 
Query q2 = query(where("foos").elemMatch(where("prop2").is("value2))

BasicQuery query = new BasicQuery(q1.getQueryObject(), q2.getQueryObject());
SampleBean result = mongoTemplate.findOne(query, SampleBean.class)

Comments

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.