Querying subdocument inside a subdocument of a collection in Mongodb - mongodb

I have the collection named companies as below.
I want to query the url corresponding to C1S1category1 . I do not know which companyName it belongs and which catergories it belongs to.
Please can you let me know what query I need to use in Mongoshell to query the document having catergoryname as C1S1category1
{"companyName": "C1",
"url": "www.com1",
"categories" : [
{"SlNo" : 1,
"url" : "www.com1",
"subcategories" : [
{
"CatergoryName":"C1S1category1",
"Url" : "www.com3"
},
{
"CatergoryName":"C1S1category2",
"Url" : "www.com3"
}
]
},
{
"SlNo" : 2,
"url" : "www.com1",
"subcategories" : [
{
"CatergoryName":"C1S2category1",
"Url" : "www.com3"
},
{
"CatergoryName":"C1S2category2",
"Url" : "www.com3"
}
]
}
]
},
{"companyName": "C2",
"url": "www.com21",
"categories" : [
{"SlNo" : 1,
"url" : "www.com22",
"subcategories" : [
{
"CatergoryName":"C2S1category1",
"Url" : "www.com23"
},
{
"CatergoryName":"C2S1category2",
"Url" : "www.com23"
}
]
},
{
"SlNo" : 2,
"url" : "www.com1",
"subcategories" : [
{
"CatergoryName":"C2S2category1",
"Url" : "www.com23"
},
{
"CatergoryName":"C2S2category2",
"Url" : "www.com23"
}
]
}
]
}

You need to use $elemMatch to get required output as following:
db.collection.find({
"categories": {
$elemMatch: {
subcategories: {
$elemMatch: {
CatergoryName: "C1S1category1"
}
}
}
}
},{"categories.$":1,"companyName":1,"url":1}).pretty()

Related

MongoDB: Filtering aggregation by field values and nested arrays

I built up a graph structure using MongoDB. I did some complex queries on this structure already, but I am struggling on selecting a subgraph of a given depth starting from a specific node via the aggregation pipeline.
I already did use the $graphLookup to get all the required nodes, which gives the following result:
{ "_id" : "O_4", "name" : "D", "type" : "Info", "links" : [ { "link" : "L_2", "objectId" : "O_1" }, { "link" : "L_4", "objectId" : "O_3" }, { "link" : "L_10", "objectId" : "O_6" } ] }
{ "_id" : "O_2", "name" : "B", "type" : "Info", "links" : [ { "link" : "L_1", "objectId" : "O_1" }, { "link" : "L_3", "objectId" : "O_3" } ] }
{ "_id" : "O_1", "name" : "A", "type" : "Info", "links" : [ { "link" : "L_1", "objectId" : "O_2" }, { "link" : "L_2", "objectId" : "O_4" } ] }
{ "_id" : "O_3", "name" : "C", "type" : "Info", "links" : [ { "link" : "L_3", "objectId" : "O_2" }, { "link" : "L_4", "objectId" : "O_4" }, { "link" : "L_5", "objectId" : "O_5" }, { "link" : "L_6", "objectId" : "O_7" } ] }
{ "_id" : "O_6", "name" : "F", "type" : "System", "links" : [ { "link" : "L_8", "objectId" : "O_7" }, { "link" : "L_9", "objectId" : "O_5" }, { "link" : "L_10", "objectId" : "O_4" } ] }
But now I want to remove the nested "link" objects (in array "links") where the "objectId" is not present in the above result, i.e. in "O_6" the link "L_8" should be removed, since the node "O_7" is not part of the subgraph.
I already tried playing around with $in, $facet and other stuff to get this problem solved, but it seems like I am unable ...
Maybe, you guys can help out?
Edit:
Just found a solution more or less - $filter does a decent job here:
{
$unwind: "$links"
}, {
$group: {
_id: null,
ids: {
$addToSet: "$_id"
},
links: {
$addToSet: "$links"
}
}
}, {
$project: {
links: {
$filter: {
input: "$links",
as: "link",
cond: {
$in: ["$$link.objectId", "$ids"]
}
}
}
}
}, {
$unwind: "$links"
}, {
$replaceRoot: {
newRoot: "$links"
}
}, {
$group: {
_id: "$link"
}
}
Returns what I needed - the list of Link-IDs:
{ "_id" : "L_1" }
{ "_id" : "L_10" }
{ "_id" : "L_3" }
{ "_id" : "L_2" }
{ "_id" : "L_4" }

Update double nested array mongodb

I have the below document which contains double nested array format. I have to update the "level" field to "Senior Engineer" when the "someKey":"somevalue" and "Company":"Company1" and "Name":"Nandhi".
Document
{
"_id" : "777",
"someKey" : "someValue",
"someArray" : [
{
"Company" : "Company1",
"someNestedArray" : [
{
"name" : "Nandhi",
"level" : "Junior Engineer"
},
{
"name" : "Rajan",
"level" : "Senio Engineer"
}
]
}],
{
"Company" : "Company2",
"someNestedArray" : [
{
"name" : "Nandhi",
"level" : "Junior Engineer"
},
{
"name" : "Rajan",
"level" : "Senio Engineer"
}
]
}
]
}
Update Query I tried
db.Test123.updateOne(
{"someKey" : "someValue","someArray.Company":"Company1"},
{$set:{"someArray.$[someNestedArray].level":"Senior Developer"}},
{arrayFilters:[{"someNestedArray.name":"Nandhi"}]}
);
Output Screenshot
As you can seen that, the modifiedCount returns 0. Please advice on this!
You need to define arrayFilter for every level of nesting, try:
db.Test123.update(
{ "someKey" : "someValue" },
{ "$set": { "someArray.$[someArrayDoc].someNestedArray.$[someNestedArrayDoc].level": "Senior Developer" } },
{ arrayFilters: [ {"someArrayDoc.Company": "Company1"}, { "someNestedArrayDoc.name": "Nandhi" } ] }
)

Distinct list of values from embedded document in mongodb

I'm going crazy... I come from the sql world an this is my first real experience with mongodb.
I have a given json/object structure (I know, this is not perfect but it has to be so because of existing data and other applications), stored in a mongodb (v3.4) with Restheart as the http frontend.
The documents look like this
{
"_id" : ObjectId("5855cbc9fc3baea81e937261"),
"_etag" : ObjectId("5855cbc99b971700050d8adc"),
"log" : [
"858489b087f7472dbb8d1012dee4cd5d.d",
NumberLong("12345678901234"),
{
"ext" : {
"text" : "someone did something at somewhere (some street 123) +38 USD",
"markup" : [
[
"user",
{
"plain" : "someone",
"team" : "master"
}
], [
"TEXT",
{
"plain" : " did something at "
}
], [
"location",
{
"name" : "somewhere",
"plain" : "some street 123",
"team" : "master"
}
], [
"TEXT",
{
"plain" : "38"
}
], [
"TEXT",
{
"plain" : "USD"
}
]
],
"category" : 1,
"team" : "master"
}
}
]
}
And I want to get a distinct list of the usern.plain names. Theoretically db.logs.distinct("log.2.ext.markup.0.1.plain") would do exactly what I need. But as far as I understand, there is no way to use db.distinct with Restheart. I tried this using views but it seems, I can not use db.distinct in views too.
This are my experiments...
{ "aggrs" : [
{ "stages" : [
{ "_$project" : { "user" : "$log.2.ext.markup.0.1.plain"}},
{ "_$unwind" : "$user"},
{ "_$unwind" : "$user"},
{ "_$unwind" : "$user"},
{ "_$unwind" : "$user"},
{ "_$unwind" : "$user"},
{ "_$unwind" : "$user"},
{ "_$group" : { "_id" : "$user"}}
],
"type" : "pipeline",
"uri" : "unique_users1"
},
{ "stages" : [
{ "_$match": { "log": { "_$exists": true, "_$ne": null }}},
{ "_$unwind" : "$log"},
{ "_$unwind" : "$log.2"},
{ "_$unwind" : "$log.2.ext"},
{ "_$unwind" : "$log.2.ext.markup"},
{ "_$unwind" : "$log.2.ext.markup.0"},
{ "_$unwind" : "$log.2.ext.markup.0.1"},
{ "_$group" : { "_id" : "$log.2.ext.markup.0.1.plain"}}
],
"type" : "pipeline",
"uri" : "unique_users2"
},
{ "stages" : [
{ "_$match" : {"log" : { "_$exists" : true }}},
{ "_$replaceRoot" : { "newRoot" : { "user": "$log.2.ext.markup.0.1.plain"}}}
],
"type" : "pipeline",
"uri" : "unique_users3"
},
{ "stages" : [
{ "_$group" : { "_id" : 1 , "users" : { "_$addToSet" : "$log.2.ext.markup.0.1.plain"}}}
],
"type" : "pipeline",
"uri" : "unique_users4"
}
]}
But results are... nothing or nearly nothing
{
"_embedded": {
"rh:result": [
{
"_id": 1,
"users": [
[]
]
}
]
},
"_returned": 1,
"_size": 1,
"_total_pages": 1
}

How select under documents via $in operator in MongoDB?

I want grab all under documents via Id's like the following SQL query:
Select * from table
where subdoc1.id in (1234, 2345, 3456)
or subdoc2.id in (1234, 2345, 3456)
Here is the structure of my document:
{
"id" : new ObjectId("234565"),
"subdocs1" : [ {
"id" : "1234",
... },
{
"id": "2345",
... }],
"subdocs2" : [ {
"id" : "3456",
... },
{
"id": "7890",
... }]
}
How would the query look like in MongoDB?
db.collection.find({
$and : [{"subdocs1._id": {"$in" : ["1234", "2345", "3456"]},
{"subdocs2._id": {"$in" : ["1234", "2345", "3456"]}}]
})
OR
db.collection.find({
$and : [{"subdocs1":{"$elemMatch" : {"$_id" : {"$in" : ["1234", "2345", "3456"]}}}},
{"subdocs2:{"$elemMatch" : {"$_id" : {"$in" : ["1234", "2345", "3456"]}}}}]
})
Here my query, that works:
db.getCollection('documents').find({
$or : [
{ "subdoc1._id" : { "$in" : [ new ObjectId("5807a60afc84c80a5ea86218"), new ObjectId("5808ac5cfc841deda17f827b") ] } },
{ "subdoc2._id" : { "$in" : [ new ObjectId("5807a60afc84c80a5ea86218"), new ObjectId("5808ac5cfc841deda17f827b") ] } },
{ "subdoc3._id" : { "$in" : [ new ObjectId("5807a60afc84c80a5ea86218"), new ObjectId("5808ac5cfc841deda17f827b") ] } },
{ "subdoc4._id" : { "$in" : [ new ObjectId("5807a60afc84c80a5ea86218"), new ObjectId("5808ac5cfc841deda17f827b") ] } }
]})
Thanx!!

Return intersection of subdocument array with user defined array?

I am trying to use Mongo Aggregation Framework to find out intersection between an array inside my document AND another user defined array.
I don't get a correct result and my guess is its because of the fact that I have array inside of an array.
Here is my data set.
My documents:
{
"_id" : 1,
"pendingEntries" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65f"),
"tags" : [
{
"tagKey" : "owner",
"tagValue" : "john"
},
{
"tagKey" : "ErrorCode",
"tagValue" : "7001"
},
{
"tagKey" : "ErrorDescription",
"tagValue" : "error123"
}
],
"entryTime" : ISODate("2016-04-04T00:26:43.167Z")
}
]
},
/* 1 */
{
"_id" : 2,
"pendingEntries" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65d"),
"tags" : [
{
"tagKey" : "owner",
"tagValue" : "peter"
},
{
"tagKey" : "ErrorCode",
"tagValue" : "6001"
},
{
"tagKey" : "JIRA",
"tagValue" : "Oabc-123"
}
],
"entryTime" : ISODate("2016-04-04T00:26:43.167Z")
}
]
},
/* 2 */
{
"_id" : 3,
"pendingEntries" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65c"),
"tags" : [
{
"tagKey" : "owner",
"tagValue" : "abc"
},
{
"tagKey" : "ErrorCode",
"tagValue" : "6001"
},
{
"tagKey" : "JIRA",
"tagValue" : "abc-123"
}
],
"entryTime" : ISODate("2016-04-04T00:26:43.167Z")
}
]
}
My Query:
db.entrylike.aggregate(
[
{ $project: { "pendingEntries.entryID": 1, "common": { $setIntersection: [ "$pendingEntries.tags", [{ "tagKey" : "ErrorCode", "tagValue" : "7001" }] ] } } }
]
)
Result:
{
"result" : [
{
"_id" : 1,
"pendingEntries" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65f")
}
],
"common" : []
},
{
"_id" : 2,
"pendingEntries" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65d")
}
],
"common" : []
},
{
"_id" : 3,
"pendingEntries" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65c")
}
],
"common" : []
}
],
"ok" : 1
}
I am not expecting first common field to be empty. Can someone let me know what is it that I am doing wrong? Or any work arounds that I can take.
I am using mongodb 3.0.8. I am aware of the fact that Mongodb 3.2 can offer some features which will fulfill my needs but 3.2 upgrade is not in our pipeline soon and I am looking to resolve this using Mongo3.0 if possible.
My goal is to either replace tags array with the common elements from the user defined list or add a new field with common elements. My am trying to to the later in my example.
The reason you the common field is empty is because your "pendingEntries" array and your user defined array have not element in common. What you really want is to return an array that contains the elements that appear in your "tags" array and your user defined array. To do that you can simply use the $map operator and apply the $setIntersection operator to each subdocument "tags" in the "pendingEntries" array.
db.entrylike.aggregate([
{ "$project": {
"common": {
"$map": {
"input": "$pendingEntries",
"as": "p",
"in": {
"entryID": "$$p.entryID",
"tags": {
"$setIntersection": [
"$$p.tags",
{ "$literal": [
{
"tagKey" : "ErrorCode",
"tagValue" : "7001"
}
]}
]
}
}
}
}
}}
])
Which returns:
{
"_id" : 1,
"common" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65f"),
"tags" : [
{
"tagKey" : "ErrorCode",
"tagValue" : "7001"
}
]
}
]
}
{
"_id" : 2,
"common" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65d"),
"tags" : [ ]
}
]
}
{
"_id" : 3,
"common" : [
{
"entryID" : ObjectId("5701b4c3c6b126083332e65c"),
"tags" : [ ]
}
]
}