I am storing some tree-structured data in MongoDB. It looks something like this:
{
"_id": 1,
"name": "foo",
"subs": [{
"name": "bar",
"subs": [{
"name": "baz"
},
{
"name": "gizmo"
}]
}]
}
{
"_id": 2,
"name": "foo",
"subs": [{
"name": "bar",
"subs": [{
"name": "gizmo"
}]
}]
}
I want to query on the subtrees, and wish only to extract the part of the tree that matches the query. In each node, there is at most one subtree that matches the query.
In this test-query, I want to find the part of the tree that matches the path "foo/bar/gizmo". So, I have tried the following:
db.Test.find({
name: "foo",
subs: {
$elemMatch: {
name: "bar",
subs: {
$elemMatch: {
name: "gizmo"
}
}
}
}
},
{
"subs.subs": {
$slice: 1
}
})
The result I get is
{
"_id": 1,
"name": "foo",
"subs": [{
"name": "bar",
"subs": [{
"name": "baz"
}]
}]
}{
"_id": 2,
"name": "foo",
"subs": [{
"name": "bar",
"subs": [{
"name": "gizmo"
}]
}]
}
whereas I actually wanted
{
"_id": 1,
"name": "foo",
"subs": [{
"name": "bar",
"subs": [{
"name": "gizmo"
}]
}]
}{
"_id": 2,
"name": "foo",
"subs": [{
"name": "bar",
"subs": [{
"name": "gizmo"
}]
}]
}
Is it possible to do this? I have tried using the $elemMatch projection operator on the subtrees, but it seems it is not currently supported by Mongo (Cannot use $elemMatch projection on a nested field (currently unsupported)).
You can use Aggregation Framework to get result as you wish. Try the following code :
db.Test.aggregate(
{$unwind : "$subs"},
{$unwind : "$subs.subs"},
{$match : {name : "foo", "subs.name" : "bar", "subs.subs.name" : "gizmo"}}
);
Result will be like :
"result" : [
{
"_id" : ObjectId("52540da2e3a2c44e082642d4"),
"name" : "foo",
"subs" : {
"name" : "bar",
"subs" : {
"name" : "gizmo"
}
}
},
{
"_id" : ObjectId("52540dd6e3a2c44e082642d5"),
"name" : "foo",
"subs" : {
"name" : "bar",
"subs" : {
"name" : "gizmo"
}
}
}
]
Related
Trying to update the nested object for the document in MongoDB.
{
"items" : [
{
"id": 1,
"name": "a",
"child": [
{ "id": 11, "name": "aa" },
{ "id": 12, "name": "bb" },
]
},
]
}
Need to update the child id to 13 whose name is "aa".
O/P, which I am trying to get
{
"items" : [
{
"id": 1,
"name": "a",
"child": [
{ "id": 13, "name": "aa" },
{ "id": 12, "name": "bb" },
]
},
]
}
Work with $[<identifier>] filtered positional operator and arrayFilters.
db.collection.update({
"items.child.name": "aa"
},
{
$set: {
"items.$[].child.$[c].id": 13
}
},
{
arrayFilters: [
{
"c.name": "aa"
}
]
})
Sample Mongo Playground
If these are the following nested documents
[
{
"_id": 5,
"name": "Wilburn Spiess",
"scores": [
{
"score": 44.87186330181261,
"type": "exam"
},
{
"score": 25.72395114668016,
"type": "quiz"
},
{
"score": 63.42288310628662,
"type": "homework"
}
]
},
{
"_id": 6,
"name": "Jenette Flanders",
"scores": [
{
"score": 37.32285459166097,
"type": "exam"
},
{
"score": 28.32634976913737,
"type": "quiz"
},
{
"score": 81.57115318686338,
"type": "homework"
}
]
},
{
"_id": 7,
"name": "Salena Olmos",
"scores": [
{
"score": 90.37826509157176,
"type": "exam"
},
{
"score": 42.48780666956811,
"type": "quiz"
},
{
"score": 96.52986171633331,
"type": "homework"
}
]
}
]
I need to access the score part 'type' = exam.
Can somebody help me with this?
If you're asking for a python program to access the score, you can print them out like:
collection = mongo_connection['db']['collection']
documents = collection.find({})
for doc in documents:
for score in doc['scores']:
if score['type'] == 'exam':
print(f'Score: {score["score"]}')
If you are trying to retrieve only the scores and ignore the rest, I'd do an $unwind on the scores, $match on the type, and then project the fields you want (or not).
db.test.aggregate([
{
$unwind: '$scores'
},
{
$match: {
'scores.type': 'exam'
}
},
{
$project: {
'name': '$name',
'score': '$scores.score'
}
}
])
This would output:
{
"_id" : 5,
"name" : "Wilburn Spiess",
"score" : 44.8718633018126
},
{
"_id" : 6,
"name" : "Jenette Flanders",
"score" : 37.322854591661
},
{
"_id" : 7,
"name" : "Salena Olmos",
"score" : 90.3782650915718
}
I have the following result. Below it would be possible to make a map joining the array each with its objectid.
{
"_id": ObjectId("597233b50e717e0585dbd94a"),
"createdAt": ISODate("2017-07-21T17:02:45.119+0000"),
"name": "cardoso",
"gender": "female",
"profile": [{
"profession": "master",
"_id": ObjectId("597233b50e717e0585dbd94b"),
"departament": ObjectId("597233b50e717e0585dbd94e")
},
{
"_id": ObjectId("59766719003e7d552fe40e8c"),
"profession": "master",
"departament": ObjectId("59766719003e7d552fe40e8b")
},
{
"_id": ObjectId("5976b8f99d8a4326c6bf1ae5"),
"profession": "master",
"departament": ObjectId("5974d8fe398e5b2fd433410f")
}
],
"Institution": {
"_id": ObjectId("597233b50e717e0585dbd94c"),
"cnpj": 64837134000144.0,
"deletedAt": false,
"departament": [{
"title": "cardoso",
"category": "Sub-17",
"_id": ObjectId("597233b50e717e0585dbd94e")
},
{
"sport": "Tênis",
"title": "novo",
"category": "Sub-12",
"_id": ObjectId("59766719003e7d552fe40e8b")
},
{
"_id": ObjectId("5974d8fe398e5b2fd433410f"),
"category": "Intercâmbio",
"title": "testeJJJ",
"sport": "natação"
}
]
}
}
I need to do the following result. I did not want to have to manipulate the result in the node.
{
"sport": "Tênis",
"profession": "master",
"title": "novo",
"category": "Sub-12",
"_id": ObjectId("59766719003e7d552fe40e8b")
}
I already tended to do something but the query ends up getting very big
The basic premise here is to "lookup" the content in the other array whilst processing via $map.
This is either done via $indexOfArray with MongoDB 3.4:
db.collection.aggregate([
{ "$addFields": {
"Institution": {
"departament": {
"$map": {
"input": "$Institution.departament",
"as": "d",
"in": {
"sport": "$$d.title",
"profession": {
"$arrayElemAt": [
"$profile.profession",
{ "$indexOfArray": [ "$profile.departament", "$$d._id" ] }
]
},
"title": "$$d.title",
"category": "$$d.category"
}
}
}
}
}}
])
In that first index we look for the "index position" from the "profile" array that matches the current value of _id on the specified field. Then extract the data at that index via $arrayElemAt.
Or using $filter and the $arrayElemAt "the other way around" with MongoDB 3.2:
db.collection.aggregate([
{ "$addFields": {
"Institution": {
"departament": {
"$map": {
"input": "$Institution.departament",
"as": "d",
"in": {
"sport": "$$d.title",
"profession": {
"$arrayElemAt": [
{ "$map": {
"input": {
"$filter": {
"input": "$profile",
"as": "p",
"cond": { "$eq": [ "$$p.departament", "$$d._id" ] }
}
},
"as": "p",
"in": "$$p.profession"
}},
0
]
},
"title": "$$d.title",
"category": "$$d.category"
}
}
}
}
}}
])
In which case the $filter reduces the array content in "profile" down to only matching elements, which should be just one. This is then extracted at the 0 index by $arrayElemAt.
Same result in either case:
{
"_id" : ObjectId("597233b50e717e0585dbd94a"),
"createdAt" : ISODate("2017-07-21T17:02:45.119Z"),
"name" : "cardoso",
"gender" : "female",
"profile" : [
{
"profession" : "master",
"_id" : ObjectId("597233b50e717e0585dbd94b"),
"departament" : ObjectId("597233b50e717e0585dbd94e")
},
{
"_id" : ObjectId("59766719003e7d552fe40e8c"),
"profession" : "master",
"departament" : ObjectId("59766719003e7d552fe40e8b")
},
{
"_id" : ObjectId("5976b8f99d8a4326c6bf1ae5"),
"profession" : "master",
"departament" : ObjectId("5974d8fe398e5b2fd433410f")
}
],
"Institution" : {
"_id" : ObjectId("597233b50e717e0585dbd94c"),
"cnpj" : 64837134000144.0,
"deletedAt" : false,
"departament" : [
{
"sport" : "cardoso",
"profession" : "master",
"title" : "cardoso",
"category" : "Sub-17"
},
{
"sport" : "novo",
"profession" : "master",
"title" : "novo",
"category" : "Sub-12"
},
{
"sport" : "testeJJJ",
"profession" : "master",
"title" : "testeJJJ",
"category" : "Intercâmbio"
}
]
}
}
I know you can count how many elements are in a collection with
collection.find().count().
However, I was wondering how can I count a certain element inside the item inside the collection. For example I have four images inside a Documents like this:
"Documents":{
"1":"image.png",
"2":"Test.jpg",
"3":"Next.png"
}
I was wondering how I can count all the items in Documents? I have tried a few things but none of them are working. Can anyone help?
Example data:
{
"name": "Oran",
"username": "Oran.Hammes",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/brandonflatsoda/128.jpg",
"email": "xxxxxx#hotmail.com",
"dob": "1953-03-21T17:40:17.020Z",
"phone": "364-846-1607",
"address": {
"street": "Schultz Stream",
"suite": "Suite 618",
"city": "North Muriel mouth",
"zipcode": "06447-1081",
"geo": {
"lat": "57.1844",
"lng": "-56.8890"
}
},
"website": "misty.net",
"company": {
"name": "Hettinger, Reilly and Stracke",
"catchPhrase": "Multi-tiered system-worthy database",
"bs": "best-of-breed evolve e-markets"
},
"Documents": [
{
"id": "1",
"name": "image.png",
},
{
"id": "2",
"name": "Test.jpg",
},
{
"id": "3",
"name": "Next.png"
}
]
}
After this comment I changed my document's structure and it looks like this:
{
"_id" : ObjectId("568703d08981f193cf343698"),
"name" : "Oran",
"username" : "Oran.Hammes",
"email" : "xxxxxxx#hotmail.com",
"dob" : "1953-03-21T17:40:17.020Z",
"phone" : "364-846-1607",
"company" : {
"name" : "Hettinger, Reilly and Stracke",
"catchPhrase" : "Multi-tiered system-worthy database",
"bs" : "best-of-breed evolve e-markets"
},
"Documents" : [
{
"id" : "1",
"name" : "image.png"
},
{
"id" : "2",
"name" : "Test.jpg"
},
{
"id" : "3",
"name" : "Next.png"
}
]
}
Generally speaking it's not a good idea to have dynamic keys in your documents. Your best bet in situation like this is mapReduce
var map = function() {
emit(this._id, Object.keys(this.Documents).length);
};
var reduce = function(key, values) {};
db.collection.mapReduce(map, reduce, { "out": { "inline": 1 } } )
Which yields:
{
"results" : [
{
"_id" : ObjectId("5686e2a98981f193cf343697"),
"value" : 3
}
],
"timeMillis" : 697,
"counts" : {
"input" : 1,
"emit" : 1,
"reduce" : 0,
"output" : 1
},
"ok" : 1
}
Definitely the best thing to do is to change your documents structure and make Documents an array of sub-documents so that the Documents field value looks like this:
"Documents": [
{
"id": "1",
"name": "image.png",
},
{
"id": "2",
"name": "Test.jpg",
},
{
"id": "3",
"name": "Next.png"
}
]
and use the .aggregate() method to $project your documents and return the number of elements in the "Documents" array using the $size operator
db.collections.aggregate([
{ "$project": { "count": { "$size": "$Documents" } } }
] )
I have the following JSON document in my mongoDB which I added with mingoimport.
I am trying to return a single element from the questions array where theQuestion equals "q1".
{
"questions": [
{
"questionEntry": {
"id": 1,
"info": {
"seasonNumber": 1,
"episodeNumber": 1,
"episodeName": "Days Gone Bye"
},
"questionItem": {
"theQuestion": "q1",
"attachedElement": {
"type": 1,
"value": ""
}
},
"options": [
{
"type": 1,
"value": "o1"
},
{
"type": 1,
"value": "o1"
}
],
"answer": {
"questionId": 1,
"answer": 1
},
"metaTags": [
"Season 1",
"Episode 1",
"Rick Grimmes"
]
}
},
{
"questionEntry": {
"id": 1,
"info": {
"seasonNumber": 1,
"episodeNumber": 1,
"episodeName": "Days Gone Bye"
},
"questionItem": {
"theQuestion": "q2",
"attachedElement": {
"type": 1,
"value": ""
}
},
"options": [
{
"type": 1,
"value": "o2"
},
{
"type": 1,
"value": "o2"
}
],
"answer": {
"questionId": 1,
"answer": 1
},
"metaTags": [
"Season 1",
"Episode 1",
"Rick Grimmes",
"Glenn Rhee"
]
}
}
]
}
I ran the query db.questions.find({"questions.questionEntry.questionItem.theQuestion" : "q1"}) but this retruned the whole document (both questionEntry's in question array!
I have tried db.questions.find({"questions.questionEntry.questionItem.theQuestion" : "q1"}, _id:0," questions.questionItem": {$elemMatch : {theQuestion: "q1"}}})
But get the following error:
Error: error: {
"$err" : "Can't canonicalize query: BadValue Cannot use $elemMatch projection on a nested field.", "code" : 17287
Is there a way I could limit the result to just the array element which contains it?
Thanks
db.questions.find({},{"questions.questionEntry.questionItem.theQuestion" : "q1"});
or
db.questions.find({"questions.questionEntry.questionItem.theQuestion" : "q1"},{'questions.$':1});
please try these.
If you want to use $elemMatch the query should be:
db.questions.find(
{"questions.questionEntry.questionItem.theQuestion" : "q1"},
{
'_id':0,
"questions": {
$elemMatch : {"questionEntry.questionItem.theQuestion": "q1"}
}
}
)