1

In command prompt I enter the following:

db.products.insert( { item: "card", qty: 15 } )

I wanted to know how would I be able to get the item value from java. I want to create a variable called item and it would know the value of it which is "card".

I am currently using MongoOperations in java but I do not know how to get only one value from MongoDB.

Pojo

@Document(collection="products") 
public class ValueServerModel{

    @Id
    private String id;

    String item;

    int qty;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public Product(String item, int qty) {
        //super();
        this.item = item;
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
    }

}

//provided by suwal

Long Shot Attempt

@Autowired
MongoOperations mongoOperations;

@PostConstruct
public List<SomeModel> getList() {
List<SomeModel> pmLst = mongoOperations.findAll(ServerModel.class);
//code above works I get a list of values based on mongo db

//attempting to retrieve one value, (stuck)
String value = mongoOperations.find("test", ValueServerModel.class);

With command prompt

I am able to get a value by using the following command:

db.products.find({}, {qty:0, _id:0})
//output ("item": "card")

I want to achieve the following:

db.products.find({}, {item})
//output should be "card".

is it possible to do what I just did above?

2

2 Answers 2

1

You can use projection to request the fields.

Something like

Query query = new Query();
query.fields().include("item").exclude("_id");
Product product = mongoOperations.findOne(query, Product.class);

This will populate the product pojo with item field.

You can use native mongo java driver to request the fields directly.

Something like

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongoClient.getDatabase(db_name);
MongoCollection<Document> collection = database.getCollection(collection_name);
String value  = collection.find().projection(Projections.include("item")).first().getString("item");
Sign up to request clarification or add additional context in comments.

3 Comments

Just attempted your example. The out put becomes [Id = null]. System.out.println(product);
Are you sure you are using the product pojo from the post ? I see Product [id=null, item=card, qty=0] on my end.
Sorry my override toString method was off. I got the same results now
1

I get that you want to get the value, but you are not specifying based on what. That is "what is your query condition". Also not sure what ServerModel and ValueServerModel classes are, but let see if this general idea helps you.

Lets say you have following structure stored after your insert query in the collection products

{
    "_id" : ObjectId("5939d5a1d0ffa3f0209fd42f"),
    "item" : "card",
    "qty" : 15
}

You will need a model representing the collection,

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="products") //this is what binds this class to your collection
public class Product {

    @Id
    private String id;

    String item;

    int qty;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    public Product(String item, int qty) {
        //super();
        this.item = item;
        this.qty = qty;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
    }

}

Now in your code you would have something like this,

// findOne returns you single instance of an object of the specified type
    Product product = mongoOperation.findOne(
            new Query(Criteria.where("item").is("card")), Product.class);

    System.out.println(product); //Output => Product [id=5939d5a1d0ffa3f0209fd42f, item=card, qty=15]

    String value = product.getItem();

    System.out.println("value is " + value);//Output => card

Lets say you want to get by id instead, so you would have something like this

Product product2 = mongoOperation.findOne(
            new Query(Criteria.where("_id").is("5939d5a1d0ffa3f0209fd42f")), 
Product.class);

    System.out.println(product2);

1 Comment

Is it possible to query a key without giving the value? ex; I want to query item. and it should respond with "card" instead of giving key and value.

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.