Mongodb: request a json object nested in an array

I am new to mongodb, and there is one thing that I cannot solve right now:
Suppose you have the following document (simplified):

{ 'someKey': 'someValue', 'array' : [ {'name' : 'test1', 'value': 'value1' }, {'name' : 'test2', 'value': 'value2' } ] } 

Which request will return a json object in which the value is 'value2'?

This means that I need this json object:

 { 'name' : 'test2', 'value': 'value2' } 

Of course, I already tried many possible queries, but none of them returned the rights, for example.

 db.test.find({'array.value':'value2'}) db.test.find({'array.value':'value2'}, {'array.value':1}) db.test.find({'array.value':'value2'}, {'array.value':'value2'}) 

Can someone help and show me what I'm doing wrong?
Thanks!

+6
source share
4 answers

Using the Positional Operator

 db.test.find( { "array.value": "value2" }, { "array.$": 1, _id : 0 } ) 

Output

 { "array" : [ { "name" : "test2", "value" : "value2" } ] } 

Using aggregation

 db.test.aggregate([ { $unwind : "$array"}, { $match : {"array.value" : "value2"}}, { $project : { _id : 0, array : 1}} ]) 

output

 { "array" : { "name" : "test2", "value" : "value2" } } 

Using the Java Driver

  MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017)); DB db = mongoClient.getDB("mydb"); DBCollection collection = db.getCollection("test"); DBObject unwind = new BasicDBObject("$unwind", "$array"); DBObject match = new BasicDBObject("$match", new BasicDBObject( "array.value", "value2")); DBObject project = new BasicDBObject("$project", new BasicDBObject( "_id", 0).append("array", 1)); List<DBObject> pipeline = Arrays.asList(unwind, match, project); AggregationOutput output = collection.aggregate(pipeline); Iterable<DBObject> results = output.results(); for (DBObject result : results) { System.out.println(result.get("array")); } 

Output

 { "name" : "test2" , "value" : "value2"} 
+12
source

Try the $ in statement as follows:

db.test.find({"array.value" : { $in : ["value2"]}})

+1
source

Use $ elemMatch and period (.) To get the required output

 db.getCollection('mobiledashboards').find({"_id": ObjectId("58c7da2adaa8d031ea699fff") },{ viewData: { $elemMatch : { "widgetData.widget.title" : "England" }}}) 
0
source

You can pass multiple search objects to matching elements to get an exact answer.

 db.test.find({'array':{$elemMatch:{value:"value2"}}) output: {'name' : 'test1','value': 'value1'} 
0
source

Source: https://habr.com/ru/post/971024/


All Articles