How can get only one single object data from double nested array in mongodb - node.js

Hi below is my database data,i want get only 1 single object data from double nested array from my mongodb database ,how can achieve this ,may I get any help?
orders collection
{
"_id" : ObjectId("63dead6020ce1a28ee7b02cf"),
"orditems" :
[
{
"_id" : ObjectId("63dead6020ce1a28ee7b02d0"),
"items" :
[
{
"item":1,
"_id" :ObjectId("63dead6020ce1a28ee7b02d1")
},
{
"item":2,
"_id" :ObjectId("63dead6020ce1a28ee7b02d2")
}
]
},
{
"_id" : ObjectId("63dfdac1ad4c2289eb9671d9"),
"items" :
[
{
"item":4,
"_id" :ObjectId("63dfdac1ad4c2289eb9671db")
},
{
"item":4,
"_id" :ObjectId("63dfdac1ad4c2289eb9671dc")
}
]
}
]
}
{
"_id" : ObjectId("63e28f086546b180ac19d6cc"),
"orditems" :
[
{
"_id" : ObjectId("63e28f086546b180ac19d6cd")
"items" :
[
{
"item":1
"_id" :ObjectId("63e28f086546b180ac19d6ce")
},
{
"item":2
"_id" :ObjectId("63e28f086546b180ac19d6cf")
},
],
}
],
}

Related

Mongo: filter documents from multiple collections and merge

I am new to mongo and NodeJS and have a use case where I want to get filtered results from multiple collection.
Advance apologies for the long post.
for ex:
collectionA
{
"_id" : "foo#gmail.com",
"name" : "Foo",
"location" : {
"coordinates" : [
-122.420170,
37.780080
],
"type" : "Point"
}
},
{
"_id" : "bar#gmail.com,
"name" : "Bar",
"location" : {
"coordinates" : [
-122.420060,
37.780180
],
"type" : "Point"
}
}
collectionB: Some attributes are not present for all the documents and hence optional
{
"_id" : "foo#gmail.com"
"AttributeA" : [
{
"name" : "AttA_Name",
"val" : "Coll_B_AttA_Val_Foo"
},
{
"name" : "AttA_Name1",
"val" : "Coll_B_AttA_Val_Foo"
}]
},
{
"_id" : "bar#gmail.com"
"AttributeA" : [
{
"name" : "AttA_Name",
"val" : "Coll_B_AttA_Val_Bar"
},
{
"name" : "AttA_Name2",
"val" : "Coll_B_AttA_Val_Bar"
}
],
"AttributeB" : [
{
"name" : "AttB_Name",
"val" : "Coll_B_AttB_Val_Bar"
}
]
}
CollectionC: Some attributes are not present for all the documents and hence optional
{
"_id" : "foo#gmail.com"
"AttributeA" : [
{
"name" : "Coll_C_AttA_Name",
"val" : "Coll_C_AttA_Val_Foo"
}]
},
{
"_id" : "bar#gmail.com"
"AttributeA" : [
{
"name" : "Coll_C_AttA_Name",
"val" : "Coll_C_AttA_Val_Bar"
}
],
"AttributeB" : [
{
"name" : "Coll_C_AttB_Name",
"val" : "Coll_C_AttB_Val_Bar"
}
]
}
I know Collection B and C schema looks the same but the purpose is different and they have to be different. DB design is not the question so I would appreciate if do not put all the focus on it.
Query:
Assume there is another user (Alan) with same attributes present as Bar that exist in the collection but is not living nearby the location of Bar.
The query I am trying to build on top of these is,
Find people living nearby from CollectionA
And Collection B, if AttributeA exist and have an element with name: AttA_Name
And in Collection C, if AttributeA exist and have an name: Coll_C_AttA_Name
In the above case I am expecting a result as
{
"_id" : "foo#gmail.com",
"name" : "Foo",
"location" : {
"coordinates" : [
-122.420170,
37.780080
],
"type" : "Point"
},
"collectionB_AttributeA" : [
{
"name" : "AttA_Name",
"val" : "Coll_B_AttA_Val_Foo"
},
{
"name" : "AttA_Name1",
"val" : "Coll_B_AttA_Val_Foo"
}]
,
"collectionC_AttributeA" : [
{
"name" : "Coll_C_AttA_Name",
"val" : "Coll_C_AttA_Val_Foo"
}]
},
{
"_id" : "bar#gmail.com,
"name" : "Bar",
"location" : {
"coordinates" : [
-122.420060,
37.780180
],
"type" : "Point"
},
"collectionB_AttributeA":[
{
"name" : "AttA_Name",
"val" : "Coll_B_AttA_Val_Bar"
},
{
"name" : "AttA_Name2",
"val" : "Coll_B_AttA_Val_Bar"
}
],
"collectionC_AttributeA":[
{
"name" : "Coll_C_AttA_Name",
"val" : "Coll_C_AttA_Val_Bar"
}
]
}
There is one way of doing is in parts:
query Collection A and get the nearby people
Loop through the result of 1 and find in CollectionB if they have AttributeA and an element with name AttA_Name and eliminate if they don't match.
Loop through the filtered results from 2 and find in CollectionC if they have AttributeA and and element with name Coll_C_AttA_Name and if they don't eliminate such documents.
Is there a way I can use aggregate to build this query as one? I tried reading and trying the aggregate but seems like my understanding is incomplete.
let result = await CollectionASchema.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ Number(long) , Number(lat) ] },
distanceField: "dist.calculated",
minDistance: 0,
maxDistance: radiusinmetres,
spherical: true
}
},
{
$lookup:
{
from: 'collectionB',
pipeline: [
{ $match : { $and: [{ AttributeA :{$exists: true}}, { [category]: { $elemMatch: { name: “AttA_Name” } } }] }},
{ $project: { AttributeA: 0 } }
],
as: "collectionB_AttributeA"
}
}
])
If you can explain if this is possible or let me know off this is the right approach that would be helpful.

update particular single subdocument in nested array in nodejs mongodb

I am new to nodejs and mongo db. I have nested subdocument type schema in mongo. Document type is Process => Subprocess => tasks => configs. These are in the format of nested arrays and can be multiple.
{
"_id" : ObjectId("5bcec0ee711fe511f4848c1d"),
"process_title" : "customer acquisition",
"subprocess" : [
{
"_id" : ObjectId("5bcec0f8711fe511f4848c1e"),
"subprocess_title" : "application",
"tasks" : [
{
"_id" : ObjectId("5bcec158711fe511f4848c1f"),
"task_title" : "pre screening",
"task_slug" : "pre-screening",
"task_configs" : [
{
"_id" : ObjectId("5bcec4b912582b01b84fe47a"),
"next_task" : "thanks"
}
]
},
{
"_id" : ObjectId("5bcec190711fe511f4848c20"),
"task_title" : "thanks",
"task_slug" : "thanks",
"task_configs" : [
{
"_id" : ObjectId("5bcec469ab23ab1fc0bbb9ed"),
"form_field" : "responseMessage",
"expression" : "=",
"expression_value" : "Approved4",
"success_task" : "signup",
"success_sub_process_id" : "5bcec0f8711fe511f4848c1e",
"fail_task" : "thanks",
"fail_sub_process_id" : "5bcec0f8711fe511f4848c1e"
}
]
},
{
"_id" : ObjectId("5bcec1c3711fe511f4848c21"),
"task_title" : "signup",
"task_slug" : "signup",
"task_configs" : [
{
"_id" : ObjectId("5bcec469ab23ab1fc0bbb9ed"),
"form_field" : "responseMessage",
"expression" : "=",
"expression_value" : "Approved4",
"success_task" : "signup",
"success_sub_process_id" : "5bcec0f8711fe511f4848c1e",
"fail_task" : "thanks",
"fail_sub_process_id" : "5bcec0f8711fe511f4848c1e"
}
]
}
]
}
],
"created_at" : ISODate("2018-10-23T06:34:22.676Z"),
"updated" : ISODate("2018-10-23T06:34:22.676Z"),
"__v" : 0
}
Now I want to update task_configs for a particular task. I am updating task_config on the basis of task_slug.
I found a way myself to update above query.
Workflow.updateOne({ "_id": new ObjectId(req.body.process_id), "subprocess._id": new ObjectId(req.body.sub_process_id), "subprocess.tasks.task_slug": req.body.task_slug },
{
$set: {
'subprocess.$.tasks.$[j].task_configs': req.body.task_configs
}
},
{
arrayFilters: [
{
"j.task_configs": req.body.task_configs
}]
})
.then(function (resp) {
console.log(resp)
res.json({ status: 'success', resp });
}).catch(function (err) {
res.status(500).json(err);
})

Mongo pull object from array inside array

i have inside my mongoDB collection this document
{
"_id" : ObjectId("5b633025579fac22e74bf3be"),
"FLAGS" : [
{
"toSent" : [
{
"_id" : ObjectId("5b633025579fac22e74bf3c2"),
"phone" : "+84404040404"
},
{
"_id" : ObjectId("5b633025579fac22e74bf3c1"),
"phone" : "+212652253403"
},
{
"_id" : ObjectId("5b633025579fac22e74bf3c0"),
"phone" : "+212123456788"
}
],
"_id" : ObjectId("5b633025579fac22e74bf3bf"),
"action" : "group_p_a"
},
{
"toSent" : [
{
"_id" : ObjectId("5b633031579fac22e74bf3c9"),
"phone" : "+212651077199"
},
{
"_id" : ObjectId("5b633031579fac22e74bf3c8"),
"phone" : "+84404040404"
},
{
"_id" : ObjectId("5b633031579fac22e74bf3c7"),
"phone" : "+212652253403"
},
{
"_id" : ObjectId("5b633031579fac22e74bf3c6"),
"phone" : "+212123456788"
}
],
"_id" : ObjectId("5b633031579fac22e74bf3c5"),
"action" : "group_p_a"
}
],
"time" : ISODate("2018-08-02T16:24:05.747+0000"),
"action_user_phone" : "+212123456788",
"idGroup" : "e534379a-1580-4568-b5ec-6eaf981538d2",
"nomGroup" : "MOH FOR EVER",
"__v" : NumberInt(0)
}
TODO
I need to remove for example this element { "_id" : ObjectId("5b633025579fac22e74bf3c2"), "phone" : "+84404040404"}
WHAT I DID
GroupEvents.update({}, {$pull:{FLAGS:{$elemMatch:{toSent:{phone: "+84404040404"} }}}},function(err,ret){
if(err)
console.log("error"+err);
if(ret)
console.log(ret);
});
It remove all what's inside toSent event if it doesn't match.
Any help please
You need to use $ positional operator instead of $elemMatch here
GroupEvents.update(
{ "Flags.toSent.phone": "+84404040404" },
{ "$pull": { "FLAGS.$.toSent": { "phone": "+84404040404" }}},
)
If you want remove from every element of FLAGS array this you need to use $[] the all positional operator
GroupEvents.update(
{ "Flags.toSent.phone": "+84404040404" },
{ "$pull": { "FLAGS.$[].toSent": { "phone": "+84404040404" }}},
)

Need to apply two group in sequence and second group should will have effect on result of first group

I want to group my data on the base of factoryId field and then each factory there will be multiple orders want to again group on basis of orderId as each order can contain multiple items. Here I am giving the example of my data and what I need and first group by which I tried.
{
"_id" : ObjectId("5b3e270c42d8004cea382e87"),
"factoryId" : ObjectId("5aa76190cef23a1561b8056c"),
"productId" : ObjectId("5aa78c66cef23a1561b80893"),
"orderId" : ObjectId("5b3e270c42d8004cea382e86"),
"generatedOrderId" : "3985-166770-4554",
"productName" : "Lakme Lotion"
},
{
"_id" : ObjectId("5b3e270c42d8004cea382e88"),
"factoryId" : ObjectId("5b39aed32832f72062e51c23"),
"productId" : ObjectId("5b3cb96139cec8341df52c4b"),
"orderId" : ObjectId("5b3e270c42d8004cea382e86"),
"generatedOrderId" : "3985-166770-4554",
"productName" : "Coke"
},
{
"_id" : ObjectId("5b3e27b07fe0d94d62b76b2a"),
"factoryId" : ObjectId("5aa76190cef23a1561b8057c"),
"productId" : ObjectId("5ac21075ac347a5fbf355028"),
"orderId" : ObjectId("5b3e27b07fe0d94d62b76b27"),
"generatedOrderId" : "3985-755507-7484",
"productName" : "Spoon"
}
And I want result as:
{
"factoryId":ObjectId("5aa76190cef23a1561b8057c"),
"orders":[
{
"orderId":ObjectId("5b3e270c42d8004cea382e86")
"items":[
{
"productName":"Lakme Lotion"
},
{
"productName":"Coke"
}
]
}
]
}
Can anyone help me with this?. Any help is appreciated.
I tried and It worked for me. Sorry
db.getCollection("transactions").aggregate(
[
{
"$group" : {
"_id" : "$orderId",
"items" : {
"$push" : "$$ROOT"
}
}
},
{
"$project" : {
"orderId" : "$_id",
"items" : "$items",
"_id" : 0
}
},
{
"$unwind" : {
"path" : "$items",
"preserveNullAndEmptyArrays" : false
}
},
{
"$group" : {
"_id" : "$items.factoryId",
"orders" : {
"$push" : "$$ROOT"
}
}
},
{
"$project" : {
"factoryId" : "$_id",
"orders" : "$orders",
"_id" : 0
}
}
]
);

query to get all _id in array in mongdb?

I have following collection
{
"_id" : ObjectId("5acdb95d5ea63a27c1facf92"),
"venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
}
{
"_id" : ObjectId("5acdb95d5ea63a27c1facf93"),
"venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
}
{
"_id" : ObjectId("5acdb95d5ea63a27c1facf91"),
"venue" : ObjectId("5acdb95d5ea63a27c1facf8c"),
"author" : ObjectId("5ac8ba3582c2345af70d4658"),
}
how to get all _id in an array having same venue
My output should be like this
{array: ['5acdb95d5ea63a27c1facf91', '5acdb95d5ea63a27c1facf91', '5acdb95d5ea63a27c1facf93']}
Try this query:
db.colelction.aggregate([
{$match:{"venue" : ObjectId("5acdb95d5ea63a27c1facf8c")}},
{$group:{_id:null, array:{$push:"$_id"}}},
{$project:{_id:0}}
])
And the output is:
/* 1 */
{
"array" : [
ObjectId("5acdb95d5ea63a27c1facf92"),
ObjectId("5acdb95d5ea63a27c1facf93"),
ObjectId("5acdb95d5ea63a27c1facf91")
]
}
db.collection.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id:{venue:'$venue'},
_ids:{$addToSet:'$_id'}
}
},
// Stage 2
{
$project: {
_ids:1,
_id:0
}
}
]
);

Resources