How to match in double nested array fields using aggregate in mongodb? - javascript

Below is the code I am trying but unable to get the desired results. matching on jobid and email.
mongoConn.aggregate({
collectionName: Collection.jobactivity,
data: [
{ $unwind: '$jobs' },
{ $match: { '$and': [{ 'jobs.jobid': candidateJobHistoryObj.jobid}, {'jobs.activity.email': candidateJobHistoryObj.candidateemail }] }},
{ $project: ({ '_id': 0, 'jobs.activity.activityname': 1, 'jobs.activity.firstname': 1, 'jobs.activity.middlename': 1, 'jobs.activity.lastname': 1, 'jobs.activity.createddatetime': 1, 'jobs.activity.createdbyuserid': 1, 'jobs.activity.modifiedtime': 1, 'jobs.activity.modifiedbyuserid': 1 }) },
{ $sort: { 'jobs.activity.createddatetime': -1 } }
],
})
Json code present in mongodb:
{
"_id" : ObjectId("61c9d42fc87b10aab2e6732a"),
"accountid" : 122,
"jobs" : [
{
"jobid" : 12,
"activity" : [
{
"firstname" : "Vikas Yadav Bhai",
"middlename" : null,
"lastname" : "Yadav",
"email" : "candidate1#abc.com",
"activityname" : "inserted the data into candidate engagement workflow",
"modifiedbyuserid" : 151,
"modifiedtime" : ISODate("2015-12-01T05:30:00.000+05:30"),
"createdbyuserid" : 151,
"createddatetime" : ISODate("2015-08-12T00:00:00.000+05:30")
},
{
"firstname" : "Vikas Yadav Bhai",
"middlename" : null,
"lastname" : "Yadav",
"email" : "candidate2#abc.com",
"activityname" : "updated the job details",
"modifiedbyuserid" : 151,
"modifiedtime" : ISODate("2015-12-01T05:30:00.000+05:30"),
"createdbyuserid" : 151,
"createddatetime" : ISODate("2015-08-12T00:00:00.000+05:30")
}
]
}
]
}
I want to match the documents where email is => candidate1#abc.com and jobid = 12

Related

Is there a way I can update mongodb document without a loop ie. with array as condition?

this is my document
{ "_id" : ObjectId("5ef05c35743df0112cbf5729"),
"doctor" : ObjectId("5e2ef5fd55e8c1043895aaf1"),
"patient" : ObjectId("5e0378d9a88e67364426be55"),
"requests" : [ { "_id" : ObjectId("5ef05c35743df0112cbf572d"),
"labTestType" : ObjectId("5ee752b9e26cbb3440b9259e"),
"result" : "",
"paymentstatus" : "Unpaid",
"createdAt" : ISODate("2020-06-22T07:22:29.664Z"),
"updatedAt" : ISODate("2020-06-22T07:22:29.664Z") },
{ "_id" : ObjectId("5ef05c35743df0112cbf572c"),
"labTestType" : ObjectId("5ee752b9e26cbb3440b925a6"),
"result" : "",
"paymentstatus" : "Unpaid",
"createdAt" : ISODate("2020-06-22T07:22:29.664Z"),
"updatedAt" : ISODate("2020-06-22T07:22:29.664Z") },
{ "_id" : ObjectId("5ef05c35743df0112cbf572b"),
"labTestType" : ObjectId("5ee752b9e26cbb3440b925b5"),
"result" : "",
"paymentstatus" : "Unpaid",
"createdAt" : ISODate("2020-06-22T07:22:29.664Z"),
"updatedAt" : ISODate("2020-06-22T07:22:29.664Z") },
{ "_id" : ObjectId("5ef05c35743df0112cbf572a"),
"labTestType" : ObjectId("5ee752b9e26cbb3440b925b6"),
"result" : "",
"paymentstatus" : "Unpaid",
"createdAt" : ISODate("2020-06-22T07:22:29.664Z"),
"updatedAt" : ISODate("2020-06-22T07:22:29.664Z") }
],
"createdAt" : ISODate("2020-06-22T07:22:29.664Z"),
"updatedAt" : ISODate("2020-06-23T06:35:06.420Z"), "__v" : 0 }
I want to update paymentstatus under requests to Paid by providing labTestType
Objectids as list of array.
Try this code this works for me
db.getCollection('your_collection').findOneAndUpdate(
{
$and: [
{ _id: new ObjectId(_id) }, //_id = "5ef05c35743df0112cbf5729"
{ 'requests.labTestType': { $in: [new ObjectId('5ee752b9e26cbb3440b9259e'), new ObjectId('5ee752b9e26cbb3440b925b5')] } }]
},
{
$set: { 'requests.$.paymentstatus': 'paid'
} //set new payment status
})
this worked for me i was missing $in property
db.getCollection('your_collection').updateMany(
{_id: newObjectId(_id)},
{$set: {"requests.$[element].paymentstatus": "Paid"}},
{ multi:true,
arrayFilters: [{ "element.labTestType": {$in: arraywithobjectIds}}]
})

Elastic Search delete a single element inside a field on _source

i`m trying to delete a element inside a field of my elastic field, current, I have this struct of data:
I need in my NODE application to delete a single element from produto_tags getting the id_produto_cor,
for example:
{
"_index" : "relatorio_recebimento_produto_hml",
"_type" : "_doc",
"_id" : "54XZ9HAB4DHa2O1nQlpk",
"_score" : 1.0,
"_source" : {
"id_usuario" : 1408,
"data_criacao" : "2020-03-19T22:10:40.465Z",
"produto_tags" : [
{
"id_produto_cor" : "2489664268",
"tags" : [ ]
},
{
"id_produto_cor" : "1000045010",
"tags" : [ ]
},
{
"id_produto_cor" : "1004600287",
"tags" : [ ]
},
{
"id_produto_cor" : "1032013410",
"tags" : [ ]
},
{
"id_produto_cor" : "2468436987",
"tags" : [ ]
}
],
"referencia_tags" : [ ],
"nome_relatorio" : "teste"
}
}
XDELETE
{
query: {
match: {
produto_tags.id_produto_cor: 489664268
}
}
}
I would expect my data to be like:
"_index" : "relatorio_recebimento_produto_hml",
"_type" : "_doc",
"_id" : "xYVD5XAB4DHa2O1ndFo1",
"_score" : 1.0,
"_source" : {
"id_usuario" : 1376,
"data_criacao" : "2020-03-16T21:32:46.369Z",
"produto_tags" : [
{
"id_produto_cor" : "1000045010",
"tags" : [ ]
},
{
"id_produto_cor" : "1004600287",
"tags" : [ ]
},
{
"id_produto_cor" : "1032013410",
"tags" : [ ]
},
{
"id_produto_cor" : "2468436987",
"tags" : [ ]
}
],
"referencia_tags" : { },
"nome_relatorio" : "teste"
}
},
...
This is my final structure
zzzzzzzzzzzzzzzzzzzz
zzzzzzzzzzzzzzzzzzzz
You can use _update_by_query
POST /index102/_update_by_query
{
"script":{
"source":"ctx._source.produto_tags.remove('1029831004')"
},
"query":{
"match_all":{} --> modify query to target specific documents
--> match_all will execute script on all documents
}
}
Query for changed structure:
iterate through produto_tags, match with specific value and store the matched object in an array (list). Then iteratate through list and remove the object from produto_tags
POST /<index_name>/_update_by_query
{
"script":{
"source":"if(ctx._source.produto_tags.size()==0) {return;} def list=[]; for(product in ctx._source.produto_tags) { if (product['id_produto_cor'] ==params.product_id){list.add(product)}} if(list.size()==0) return; for(d in list){ctx._source.produto_tags.remove(ctx._source.produto_tags.indexOf(d))}",
"params" : {
"product_id" : "2468436987"
}
},
"query":{
"match_all":{} --> to select specific documents
}
}

Find and remove nested level

I want to find and remove the value, where my id is "5cc6d9737760963ea07de411"
my data:
[
{
"products" : [ {
"id" : "5cc6d9737760963ea07de411",
"quantity" : 1,
"totalPrice" : 100,
},
{
"id" : "5cc6d9737760963ea07de412",
"quantity" : 2,
"totalPrice" : 200,
}
],
"isCompleted" : false,
"_id" : "5cc7e4096d7c2c1f03570a2f"
},
{
"products" : [{
"id" : "5cc6d9737760963ea07de414",
"quantity" : 1,
"totalPrice" : 100,
},
{
"id" : "5cc6d9737760963ea07de4133",
"quantity" : 2,
"totalPrice" : 200,
}
],
"isCompleted" : false,
"_id" : "5cc7e4096d7c2c1f03570a2f"
}
]
i tried:
Schema.findOneAndUpdate({"products.id": "5cc6d9737760963ea07de411"},
{ $pull: {"products.$.id": "5cc6d9737760963ea07de411" })
but it's not working.
Now you don't need to use .dot notation. Instead you need to use "absolute" object structures:
Schema.findOneAndUpdate(
{ "products.id": "5cc6d9737760963ea07de411" },
{ "$pull": { "products": { "id": "5cc6d9737760963ea07de411" }}}
)

Mongoose (MongoDB) - Error: Can't use $each with Number

I've to push a given array of Number values into a selected Document inside my MongoDB database.
The Document that I'm going to update as the following structure:
{
"_id" : {
"id" : 17,
"type" : "f"
},
"__v" : 0,
"created_at" : ISODate("2017-03-22T11:16:21.403Z"),
"token" : {
"expDate" : ISODate("2017-12-31T00:00:00Z"),
"token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImFsYWRpbkBjb25zb3J6aW9jZXIuaXQiLCJleHAiOjE1MTQ2Nzg0MDB9.QvbT146bA_KH5XA7MH8ASXm9cr3sPZChJ3prYyDireI"
},
"updated_at" : ISODate("2017-07-24T09:42:33.741Z"),
"plots" : {
"idPlot" : [
23570,
23475
]
},
"machines" : [
{
"idPlotBind" : 1,
"ip" : "",
"mac" : "18-5F-00-4A-FE-F4",
"irrId" : 31,
"_id" : ObjectId("59084f527d634d301338aac6"),
"addr" : "pialadin.ddns.net"
},
{
"idPlotBind" : null,
"ip" : "",
"mac" : "12-01-02-FE-AB-B2",
"irrId" : 35,
"_id" : ObjectId("59084f7d7d634d301338aac7")
}
]
}
I'm using the Mongoose library for JS, and the accused query is this one:
userSchema.findOneAndUpdate({$and:[{ '_id.id': resData.PlotRows.IdUser}, {'_id.type': 'f'}]},{$addToSet:{'plots.$.idPlot': {$each: plotData}}}, {upsert: false}, function(err, usr){
if(err){
console.log(err);
return;
}
});
But when I try to execute it, gives me back:
Error: Can't use $each with Number

mongodb: update nested field, which is given by two variables

I need to set a field content to the point element given by the id.
{
"_id" : "kuwBhxAwEsJxc6oXc",
"points" : [
{
"id" : "xdB8TbFweTbc9fecg",
"pos" : [
604,
169
]
},
{
"id" : "uLoorpzQWm49KZ4w3",
"pos" : [
197,
176
]
}
}
}
So I got docId = kuwBhxAwEsJxc6oXc, pointId = uLoorpzQWm49KZ4w3 and content = 'anything'.
I tried this:
Collection.update(
{ _id: docId, 'points.id': pointId },
{ $set: { content: content } }
);
The result should be:
{
"_id" : "kuwBhxAwEsJxc6oXc",
"points" : [
{
"id" : "xdB8TbFweTbc9fecg",
"pos" : [
604,
169
]
},
{
"id" : "uLoorpzQWm49KZ4w3",
"pos" : [
197,
176
],
"content": "anything"
}
}
}
You need to use the $ operator in your update like this:
Collection.update(
{_id: docId, 'points.id': pointId},
{$set: {'points.$.content': content}}
);

Categories