I have updateMany function as follows
Article.updateMany({author: userId}, {author: anonym}, function(err, updated) {
if (err) {
res.send(err);
} else {
res.send(updated);
}
});
userId is = 6068b57dbe4eef0b579120c7
anonym is = 6069870676d6320f39e7e5a2
for testing purposes I have a single article in MongoDB as follows
db.articles.find()
{ "_id" : ObjectId("6068b591be4eef0b579120c8"), "favoritesCount" : 1, "comments" : [ ], "tagList" : [ ], "title" : "Martin", "description" : "Testib", "body" : "Asju", "author" : ObjectId("6068b57dbe4eef0b579120c7"), "slug" : "martin-2hzx78", "createdAt" : ISODate("2021-04-03T18:36:01.977Z"), "updatedAt" : ISODate("2021-04-03T18:53:29.809Z"), "__v" : 0 }
You can see that article has "author" : id field in it which currently shows userId as author.
I want to update that field and transfer authorship to anonym user.
When I send this request to postman I get following response
{
"n": 0,
"nModified": 0,
"ok": 1
}
And database remains unchanged. What am I doing wrong here ?
Related
I have a Mongo collection which has this document structure:-
{
"_id" : ObjectId("5d5e5f1dfc325d4018302293"),
"status" : "PENDING",
"workflowJourney" : [
{
"_id" : ObjectId("5d5e5f1dfc325d401830229c"),
"workflowDate" : ISODate("2019-08-22T09:23:41.491Z"),
"workflowType" : "Email",
"workflowDescription" : "Email sent to Joe Bloggs",
"workflowRecipient" : {
"employeeNumber" : "12345",
"firstName" : "Joe",
"surname" : "Bloggs",
"emailAddress" : "joe.blogs#example.com"
},
"workflowSubject" : "Invoice Approval Required (2112)",
"workflowHtmlContent" : "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitiona..."
},
{
"_id" : ObjectId("5d5e5f1dfc325d401830229d"),
"workflowDate" : ISODate("2019-08-22T09:23:41.507Z"),
"workflowType" : "Email",
"workflowDescription" : "Email sent to Jane Bloggs",
"workflowRecipient" : {
"employeeNumber" : "56789",
"firstName" : "Jane",
"surname" : "Bloggs",
"emailAddress" : "jane.bloggs#example.com"
},
"workflowSubject" : "Invoice Approval Required (2112)",
"workflowHtmlContent" : "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitiona..."
}
],
"approvals" : [],
"__v" : 1
}
I'm trying to create a query which will get a single workflowJourney. At the point of executing the query, I will already know the _id of both the main document and the workflowJourney subdocument, so I could use either/both of of these in my query.
The issue is, for this development project we are using Azure Cosmos and the query that I would expect to work is giving strange results.
If I run this in pure Mongo:-
db.getCollection('Invoices').find(
{"workflowJourney._id": ObjectId("5d5e5fd907ba93320cc54198")},
{"workflowJourney.$": 1.0}
);
I get this nice result back:-
{
"_id" : ObjectId("5d5e5f1dfc325d4018302293"),
"workflowJourney" : [
{
"_id" : ObjectId("5d5e5f1dfc325d401830229d"),
"workflowDate" : ISODate("2019-08-22T09:23:41.507Z"),
"workflowType" : "Email",
"workflowDescription" : "Email sent to Jane Bloggs",
"workflowRecipient" : {
"employeeNumber" : "56789",
"firstName" : "Jane",
"surname" : "Bloggs",
"emailAddress" : "jane.bloggs#example.com"
},
"workflowSubject" : "Invoice Approval Required (2112)",
"workflowHtmlContent" : "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitiona..."
}
]
}
Running the same query in Azure Cosmos (database contains the same data), I get this:-
{
"_id" : ObjectId("5d5e5f1dfc325d4018302293"),
"workflowJourney" : [
{},
{}
]
}
So, no useful results. I know that Cosmos DB is more of a Mongo emulator rather than a pure implementation. But I guess what I am trying to achieve is a fairly common scenario; I wonder if anyone has any suggestions on how I could re-write my query to get the result I need?
Many thanks
Glen
Okay, so I've achieved what I need to do by doing the filtering from the Node level instead. I guess the filter queries are really designed for returning entire documents rather than filtering information from within a single document.
Example:-
router.get('/emailPreview/:invoiceId/:workflowJourneyItemId', (req, res, next) => {
Invoice.findOne({ "_id": req.params.invoiceId })
.then(invoice => {
if(invoice) {
const emailHtml = invoice.workflowJourney.filter((item) => {
return item.id === req.params.workflowJourneyItemId;
})[0].workflowHtmlContent;
res.status(200).set('Content-Type', 'text/plain').send(emailHtml);
} else {
res.status(404).json({ Error: 'Email not found'});
}
}).catch(err => {
res.status(404).json({ Error: 'Email not found'});
})
});
I have documents in which I would like to update the hostUser with one of the members of the document,also have to delete the record from the member document and add the chips of the deleted member in the club chips.
Here is the sample document.
{
"_id" : "1002",
"hostUser" : "1111111111",
"clubChips" : 10000,
"requests" : {},
"profile" : {
"clubname" : "AAAAA",
"image" : "0"
},
"tables" : [
"SJCA3S0Wm"
],
"isDeleted" : false,
"members" : {
"1111111111" : {
"chips" : 0,
"id" : "1111111111"
},
"2222222222" : {
"chips" : 0,
"id" : "2222222222"
}
}
}
This is what I have tried.
db.getCollection('test').updateMany({"hostUser":"1111111111"},
{"$set":{"hostUser":"2222222222"},"$unset":{"members.1111111111":""}})
This is how you would handle unset and set in a single call to updateMany. Can you please clarify what you meant by "check if the values exist in the member field"?
db.getCollection('test').updateMany(
{"hostUser":"1111111111"},
{
'$set': {"hostUser":"2222222222"} ,
'$unset': {"members.1111111111":""}
}
)
I have two collections one is websites which stores information like:
{
"_id" : ObjectId("5ac5efd6a37efa4c0e28f5aa"),
"main_id" : 3,
"status" : "",
"website" : "http://test.com",
"last_access_time" : "2018-04-16 17:49:03",
"links" : [
{
"link_id" : "test-1",
"link" : "test1.html"
},
{
"link_id" : "test-2",
"link" : "test.html"
}
]
}
And another is website_info in which I want store info like:
{
"_id" : ObjectId("5ad72ddecf45b60dffcbf9f2"),
"main_id" : 3,
"last_access_time" : "2018-04-18 15:37:02",
"test-1" : {
"no_of_links" : 55,
"links_2" : [
{
"link" : "/home",
"link_id" : "secnd-1",
},
{
"link" : "/login",
"link_id" : "secnd-2",
},
{
"link" : "/services",
"link_id" : "secnd-3",
}
]
},
"test-2" : {
"no_of_links" : 55,
"links_2" : [
{
"link" : "/home",
"link_id" : "secnd-1",
},
{
"link" : "/login",
"link_id" : "secnd-2",
},
{
"link" : "/services",
"link_id" : "secnd-3",
}
]
}
}
I am using Python3 and mongoDB.
Here I want to check the field like "link_id" which is "test-1" in the website_info for main_id = 3 exists or not. If it is exists I will update for same, if does not exists I want to insert new record set.
The thing is how to check whether field "test-1" (which is the value from websites collection) in website_info collection exists or not.
Help is appreciated.
Here in my case, link_id will be unique in website_info collection. So no need to check for main_id, only checking for link_id solved my issue, like:
#classmethod
def find_link(self, link_id):
cursor = self.db.collection.find({link_id: {'$exists': True}} )
results = list(cursor)
return results
And check for exists like:
if(len(is_exists)>0):
#do if exists
in shell / robomongo
db.mycol.find({_id:"jodi"},{
"progress":{
$elemMatch:{
"status":"todo"
}
}
});
and the
result
this my publish
Meteor.publish('mycol', function() {
if(!this.userId)
return null;
coli = Coli.find({clientId:this.userId});
return coli;
});
and my helper
Coli.find({_id:"jodi"},{
"progress":{
$elemMatch:{
"status":"todo"
}
}
}).fetch()
result from console log(meteor)result
i want show only status todo only
not all
if i running on my console(robomongo) its work
but if i running on my script,all data show (not only status todo)
and this my db
{
"_id" : "jodi",
"clientId" : "BdTw5TtipGkodGLNY",
"project" : "jodi",
"progress" : [
{
"_id" : "ewCzYjeid9G5vpqNy",
"createdAt" : "2016-02-22T12:41:56+07:00",
"status" : "todo",
"title" : "jodi",
"detail" : "jodi"
},
{
"_id" : "ewCzYjeid9G5vpqsNy",
"createdAt" : "2016-02-22T12:41:56+07:00",
"status" : "doing",
"title" : "jodi",
"detail" : "jodi"
}
]
}
i want only show data array in status : todo
in shell it works but in my script status other than todo also appeared
Try this:
Coli.find({_id:"jodi"},
{"progress":{$elemMatch:{"status":"todo"}} },
{fields:{"progress.$": 1}}
).fetch();
thanks everyone
this my fixed code
Coli.find({
"progress":{
$elemMatch:{
"status":"doing"
}
}
})
I subscribed to my servers's publication as follows:
Template.observedQuestions.onCreated(function(){
var self = this;
self.autorun(function(){
self.subscribe('observedQuestionsFeed');
});
});
Now I need to fetch my data using helper function:
Template.observedQuestions.helpers({
observedQuestionsList : function(){
questions = Questions.find({
observedByUsers : {$exists: true,$elemMatch:{$eq:Meteor.userId()}}});
return questions;
}
});
but it does not work due to $eq being not recognised in minimongo.
How to solve it?
doc sample:
{
"_id" : "rP4JP8jkprwwi3ZCp",
"qUserId" : "NLLW3RBXqnbSGuZ3n",
"type" : "question",
"date" : ISODate("2016-02-13T11:23:10.845Z"),
"subject" : "test",
"question" : "test",
"replies" : [
{
"rID" : "LphcqKnkTHf25SCwq",
"rUserID" : "NLLW3RBXqnbSGuZ3n",
"date" : ISODate("2016-02-13T11:23:10.847Z"),
"answer" : "reply1."
},
{
"rID" : "HxaohnEgxwNJLtf2z",
"rUserID" : "NLLW3RBXqnbSGuZ22",
"date" : ISODate("2016-02-13T11:23:10.848Z"),
"answer" : "reply2"
}
],
"observedByUsers" : [ "Bi24LGozvtihxFrNe" ]
}
Judging from your sample Questions document, the field observedByUsers is a simple array which contains user IDs.
As a result, you could simply use the following query:
Questions.find({observedByUsers: Meteor.userId()});