Mongodb return objectId as string - mongodb

db.getCollection('User').find({
"userId" : ObjectId("5a141ac4048378xb52c3e5a9"),
"userRole" : "ADMIN",
"Id" : "1234567890"})
result:
{
"userId" : ObjectId("5a141ac4048378xb52c3e5a9"),
"userRole" : "ADMIN",
"Id" : "1234567890"
}
Expecting output:
{
"userId" : "5a141ac4048378xb52c3e5a9",
"userRole" : "ADMIN",
"Id" : "1234567890"
}
I am very new to mongodb i nedded to return objectId as String ,i neeed some suggestion to do that.

It can be done simply using the below approach
db.User.find({"userId": objectId("5a141ac4048378ab52c3e5a9")}).map(
function(doc) {
return { "userId": doc.userId.str}
});
Please see ObjectId for more methods

You can try use a aggregation
But ObjectId isn't strings, it's just numbers, why you want present it as string?

Related

how to update one table with the _id from another table in Mongodb

I exported data from a MySQL database into JSON and imported it into MongoDB. The problem:
When I imported clients, MongoDB created its own _id field (I know this is built in functionality, but MySQL used a clientID, autoincrementing integer).
SO, when I imported my appointments collection, the clientID was renamed oldClientID. I'd like the clientID field to be the ObjectID of the corresponding client.
My schemas:
const apptSchema = new mongoose.Schema({
ID: Number,
clientID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Client'
},
oldClientID: Number,
...other field data
});
const clientSchema = new mongoose.Schema({
ID: Number,
familyID: Number,
first: String,
last: String,
});
Sample Patient Data:
{
"_id" : ObjectId("5d82240f7c8ddd03b62aee6a"),
"ID" : 18,
"familyID" : 6,
"first" : "Jane",
"last" : "Doe"
}
Sample Appointment Data
{
"_id" : ObjectId("5d82c8b95627367d122087f9"),
"ID" : 1885,
"oldPatientID" : 18,
"scheduled" : ISODate("2015-08-05T11:20:00Z"),
"note" : ""
},
{
"_id" : ObjectId("5d82c8b95627367d122088a8"),
"ID" : 2066,
"oldPatientID" : 18,
"scheduled" : ISODate("2015-09-17T16:00:00Z"),
"note" : ""
}
What appointments should look like:
{
"_id" : ObjectId("5d82c8b95627367d122087f9"),
"ID" : 1885,
"clientID": ObjectId("5d82240f7c8ddd03b62aee6a"),
"oldPatientID" : 18,
"scheduled" : ISODate("2015-08-05T11:20:00Z"),
"note" : ""
},
{
"_id" : ObjectId("5d82c8b95627367d122088a8"),
"ID" : 2066,
"clientID" : ObjectId("5d82240f7c8ddd03b62aee6a"),
"oldPatientID" : 18,
"scheduled" : ISODate("2015-09-17T16:00:00Z"),
"note" : ""
}
I am open to learning how to achieve this in the mongo shell or using mongoose in express (or if there is another cool way, like in Robo3T).
MongoDB will always use _id as the primary key, this behavior cannot be overwritten, though you can use the _id with values from your custom id. Though this might be confusing, it is better to use indexing on your custom id, and you don't need to use ObjectId for the custom index field, but can use your own custom id schema, like UUID or an incrementing integer value etc. though it has to be generated/incremented by you or some framework, like JPA
Check Indexes
For Mongoose, you can do;
new mongoose.Schema({
customId: { type: Number, index: true }
...other field data
});
with index: true
Ok, this worked out for me, although I'm sure there has to be an easier way:
db.getCollection("appts").aggregate(
[
{
"$lookup" : {
"from" : "clients",
"localField" : "clientID",
"foreignField" : "ID",
"as" : "CLIENT"
}
},
{
"$lookup" : {
"from" : "appttypes",
"localField" : "type",
"foreignField" : "ID",
"as" : "TYPE"
}
},
{
"$lookup" : {
"from" : "apptstatuses",
"localField" : "status",
"foreignField" : "ID",
"as" : "STATUS"
}
},
{
"$project" : {
"_id" : "$_id",
"clientID" : "$CLIENT._id",
"scheduled" : "$scheduled",
"note" : "$note",
}
},
{
"$out" : "apptslinked"
}
]
);
Then I exported that as JSON, dropped the appts table, and did a mongoimport using that file.

Mongodb copy field to another array field type [duplicate]

This question already has answers here:
Update MongoDB field using value of another field
(12 answers)
How do I perform the SQL Join equivalent in MongoDB?
(19 answers)
Closed 3 years ago.
I want to create a migration script that able to copy from Project assignedTo field to Project assignedMultiple but inserted in an array with the users detail on it and assignedTo field will be null. assignedTo field will be deprecated since we were gonna use assignedMultiple.
This is my users table:
User:
{
"username" : "usertest",
"firstName" : "Stack",
"lastName" : "Overflow",
"company" : "",
"country" : "",
"id" : ObjectId("this_is_usertest_id")
}
Project:
{
"name" : "Project",
"assignedTo" : ObjectId("this_is_usertest_id"),
"assignedMultiple" : [],
"id" : ObjectId("someid")
}
Expected Output:
{
"name" : "Project",
"assignedTo" : null,
"assignedMultiple" : [{
"username" : "usertest",
"firstName" : "Stack",
"lastName" : "Overflow",
"company" : "",
"country" : "",
"id": ObjectId("this_is_usertest_id")
}]
"id" : ObjectId("someid")
}
This is what I have tried so far but nothing happens and giving me an error: failed to execute a script. TypeError: db.user.findOne(...) is null but when I try to use print(project) it prints the projects with data.
This one is based on this link MongoDB : how to set a new field equal to the value of another field, for every document in a collection
db.project
.find().forEach(function(project)
{
if (project.assignedTo) {
db.user.findOne({ where: { id: project.assignedTo } })
.forEach(function(user) {
var userObj = {
"username" : user.username,
"firstName" : user.firstName,
"lastName" : user.lastName,
"company" : user.company,
"country" : user.country,
"id" : user.id
};
db.getCollection('project').update(
{"_id" : project.id}, {$addToSet : {assignedMultiple : [...project.assignedMultiple, { "_id": project.assignedTo }]}}
)
});
}
});
Thank you in advance!

Firebase query ordering not working properly

Basically I have played with Firebase for the past week, and I recently stumbled upon the 'queryOrderedByChild()' that as far as I know - allows you to sort data in firebase. However, I seem to not get the proper results. My Firebase data looks like this:
{
"names" : {
"-KHVUwXdVPHmrO_O5kil" : {
"id" : "0",
"name" : "Jeff"
},
"-KHVV7lCeac0cZNMi9fq" : {
"id" : "3",
"name" : "Stig"
},
"-KHVVCjXgl0XxasVOHF1" : {
"id" : "13",
"name" : "Ali"
},
"-KHVVJtyUO-yJZiompJO" : {
"id" : "7",
"name" : "Hannah"
},
"-KHVVR8tMSO1Oh7R8tR1" : {
"id" : "2",
"name" : "Amanda"
}
}
}
, and my code looks like this:
ref.childByAppendingPath("names")
.queryOrderedByChild("id")
.observeEventType(.ChildAdded) { (snapshot:FDataSnapshot!) in
if let myID = snapshot.value["id"] as? String {
print(myID)
}
The output is still in a random order, displaying: 0, 2,7,1,8,4 - Isn't this supposed to be numeric? What am I doing wrong? How can I sort it so it get's numeric either ascending or descending?
You say that you're ordering by a number, but the value of your id property is stored as a string.
Since you're storing them as a string, they will be returned in lexicographical order.
If you want them to be in numerical order, you should store them as numbers
"-KHVUwXdVPHmrO_O5kil" : {
"id" : 0,
"name" : "Jeff"
},
Alternatively, you could store the ids as zero-padded strings:
{
"names" : {
"-KHVUwXdVPHmrO_O5kil" : {
"id" : "0000",
"name" : "Jeff"
},
"-KHVV7lCeac0cZNMi9fq" : {
"id" : "0003",
"name" : "Stig"
},
"-KHVVCjXgl0XxasVOHF1" : {
"id" : "0013",
"name" : "Ali"
},
"-KHVVJtyUO-yJZiompJO" : {
"id" : "0007",
"name" : "Hannah"
},
"-KHVVR8tMSO1Oh7R8tR1" : {
"id" : "0002",
"name" : "Amanda"
}
}
}
Since the strings are all the same length, they will be sorted in the correct order. But you'll have to decide on the length of the string/maximum id value in the latter solution, so it seems worse.
If you using order by child you going to order your id you no going to touch it's value.
Then maybe you have to try something like
(FIRDatabaseQuery *) queryOrderedByValue
queryOrderedByValue: is used to generate a reference to a view of the data that's been sorted by child value.

meteor client find is not working due to $eq

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()});

How to update particular array element in MongoDB

I am newbie in MongoDB. I have stored data inside mongoDB in below format
"_id" : ObjectId("51d5725c7be2c20819ac8a22"),
"chrom" : "chr22",
"pos" : 17060409,
"information" : [
{
"name" : "Category",
"value" : "3"
},
{
"name" : "INDEL",
"value" : "INDEL"
},
{
"name" : "DP",
"value" : "31"
},
{
"name" : "FORMAT",
"value" : "GT:PL:GQ"
},
{
"name" : "PV4",
"value" : "1,0.21,0.00096,1"
}
],
"sampleID" : "Job1373964150558382243283"
I want to update the value to 11 which has the name as Category.
I have tried below query:
db.VariantEntries.update({$and:[ { "pos" : 117199533} , { "sampleID" : "Job1373964150558382243283"},{"information.name":"Category"}]},{$set:{'information.value':'11'}})
but Mongo replies
can't append to array using string field name [value]
How one can form a query which will update the particular value?
You can use the $ positional operator to identify the first array element to match the query in the update like this:
db.VariantEntries.update({
"pos": 17060409,
"sampleID": "Job1373964150558382243283",
"information.name":"Category"
},{
$set:{'information.$.value':'11'}
})
In MongoDB you can't adress array values this way. So you should change your schema design to:
"information" : {
'category' : 3,
'INDEL' : INDEL
...
}
Then you can adress the single fields in your query:
db.VariantEntries.update(
{
{"pos" : 117199533} ,
{"sampleID" : "Job1373964150558382243283"},
{"information.category":3}
},
{
$set:{'information.category':'11'}
}
)