Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to query a collection using operands AND'd together. I've got the shell version working:

db.widgets.find({color: 'black, shape: 'round', weight: 100})

I'm unable to find the Java equivalent (using the native driver). I've tried various things, but here is my latest attempt:

// Find all black, round widgets with weight 100
List<BasicDBObject> criteria = new ArrayList<BasicDBObject>();
criteria.add(new BasicDBObject("color", "black"));
criteria.add(new BasicDBObject("shape", "round"));
criteria.add(new BasicDBObject("weight", 100));

DBCursor cur = widgets.find(new BasicDBObject("$and", criteria));

// Get all matching widgets and put them into a list
List<Widget> widgetList = new ArrayList<Widget>();
DBCursor cur = widgets.find(andQuery);
while (cur.hasNext()) {
  widgetList.add(new Widget(cur.next()));
}

if (widgetList.isEmpty())
  System.out.println("No results found");

Any ideas what is wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
195 views
Welcome To Ask or Share your Answers For Others

1 Answer

BasicDBObject criteria = new BasicDBObject();
criteria.append("color", "black");
criteria.append("shape", "round");
criteria.append("weight", 100);

DBCursor cur = widgets.find(criteria);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...