I have this obj
I have existing record
{
"_id":"xxxx",
"industry" : "Information Technology and Services",
"name" : "dsdds",
"profession" : "Information Technology and Services Profession Two",
"self_employed" : true,
"sex" : "M"
}
I want to update the object with {loc:"sss",db:"sss",bio:"fsdf"} as profile object like below
{
"user_id":"xxxx",
"industry" : "Information Technology and Services",
"name" : "dsdds",
"profession" : "Information Technology and Services Profession Two",
"self_employed" : true,
"sex" : "M",
"profile":{loc:"sss",db:"sss",bio:"fsdf"}
}
I tried with this
User.update({user_id:"xxxx"},{$set:{"profile":{user:"ssa",sss:"dsd"}}})
User.update({user_id:"xxxx"},{$set:{"profile":profile}})
both are returning 1 but not inserting record.
what is wrong in my command?
In my terminal
User.update({user_id:"JvH4YMBJmZrKWPhig"},{$set:{"profile":{user:"ssa",sss:"dsd"}}})
1
> User.findOne({user_id:"JvH4YMBJmZrKWPhig"})
{ _id: 'ye4uzZYXT5PCtcNrs',
company: 'ghghfh',
dob: '703621800',
hubs: [ 'AcztzE8W3hFTeTyz8' ],
industry: 'Computer Software',
job_title: 'Software Engineer',
name: 'ss',
profession: 'Computer Software Profession One',
self_employed: false,
sex: 'M',
user_id: 'JvH4YMBJmZrKWPhig' }
Try with
var finde = User.findOne({user_id:"JvH4YMBJmZrKWPhig"})
So try with one of this.
Meteor.users.update({_id:finde._id}, {$set: {profile: {value1: 'value1', value2: 'value2'}}});
or if you are using another Collection different to Accounts users
Using object on the update.
var values = {
value:"value1",
value2:"value2"
}
User.update({_id:finde._id},{$set: {profile: {values}}});
Related
We have author collection which contains author information for all the authors. We created text index using following
db.getCollection('contributors').createIndex(
{
display_name:"text",
first_name: "text",
last_name: "text"
},
{
weights: {
display_name: 10,
first_name: 5,
last_name:5
},
name: "Contributor_FTS_Index"
}
)
Here is sample data we have
{
"_id" : ObjectId("5eac8232eb5aca201f104bfb"),
"firebrand_id" : 54529588,
"agents" : null,
"created" : ISODate("2020-05-01T20:10:26.762Z"),
"display_name" : "Grace Octavia",
"email" : null,
"estates" : null,
"first_name" : "Grace",
"item_type" : "Contributor",
"last_name" : "Octavia",
"phone" : null,
"role" : 1,
"short_bio" : "GRACE OCTAVIA is the author of unforgettable novels that deal with the trials and tribulations of love, friendship, and what it means to be true to yourself. Her second novel, His First Wife, graced the Essence® bestseller list and also won the Best African-American Fiction Award from RT Book Reviews. A native of Westbury, NY, she now resides in Atlanta, GA, where there is never any shortage of material on heartache and scandal. Grace earned a doctorate in English, Creative Writing at Georgia State University in Atlanta and currently teaches at Spelman College. Visit her online at GraceOctavia.net or follow her on Twitter #GraceOctavia2.",
"slug" : "grace-octavia",
"updated" : ISODate("2020-08-05T10:10:27.691Z"),
"deleted" : false
}
{
"_id" : ObjectId("5ada44aa2ad4b3e3d0ae3daf"),
"item_type" : "Contributor",
"role" : 1,
"short_bio" : "",
"firebrand_id" : 41529135,
"display_name" : "Grace Octavia",
"first_name" : "Grace",
"last_name" : "Octavia",
"slug" : "grace-octavia",
"updated" : ISODate("2020-09-22T16:19:57.319Z"),
"agents" : null,
"estates" : null,
"deleted" : false,
"email" : null,
"phone" : null
}
{
"_id" : ObjectId("58e6ee27afbe421347a11834"),
"item_type" : "Contributor",
"role" : 1,
"short_bio" : "Octavia E. Butler (1947–2006) was a bestselling and award-winning author, considered one of the best science fiction writers of her generation. She received both the Hugo and Nebula awards, and in 1995 became the first author of science fiction to receive a MacArthur Fellowship. She was also awarded the prestigious PEN Lifetime Achievement Award in 2000. Her first novel, <i>Patternmaster</i> (1976), was praised both for its imaginative vision and for Butler’s powerful prose, and spawned four prequels, beginning with <i>Mind of My Mind</i> (1977) and finishing with <i>Clay’s Ark</i> (1984).<br /><br /> Although the Patternist series established Butler among the science fiction elite, it was <i>Kindred</i> (1979), a story of a black woman who travels back in time to the antebellum South, that brought her mainstream success. In 1985, Butler won Nebula and Hugo awards for the novella “Bloodchild,” and in 1987 she published <i>Dawn</i>, the first novel of the Xenogenesis trilogy, about a race of aliens who visit earth to save humanity from itself. <i>Fledgling</i> (2005) was Butler’s final novel. She died at her home in 2006.",
"firebrand_id" : 11532005,
"display_name" : "Octavia E. Butler",
"first_name" : "Octavia",
"last_name" : "Butler",
"slug" : "octavia-e-butler",
"updated" : ISODate("2020-09-23T04:06:18.857Z"),
"image" : "https://s3.amazonaws.com/orim-book-contributors/11532005-book-contributor.jpg",
"agents" : [
{
"name" : "Heifetz, Merrilee",
"primaryemail" : "mheifetz#writershouse.com",
"primaryphone" : "212-685-2605"
}
],
"estates" : [
{
"name" : "Estate of Octavia E. Butler",
"primaryemail" : "",
"primaryphone" : ""
}
],
"deleted" : false,
"email" : null,
"phone" : null
}
When we try to execute something like following;
db.getCollection('contributors').find({ $text: { $search: "oct" }})
it don't return any document. But if search for
db.getCollection('contributors').find({ $text: { $search: "octavia" }})
it returns all the document.
Our requirement is to give search result based on search term user entering. So it can be oc, oct, octav
Populer way to use this type of search Instead of $text so try like This,
db.contributors.find({
"$or": [
{
display_name: {
$regex: "oct",
$options: "i"
}
}
// add more fields objects same as above
]
});
You picked the wrong tool. Text search in mongo uses whole words. Read more about mongo tokenizer at https://docs.mongodb.com/manual/core/index-text/#tokenization-delimiters
The part-word index requires ngram tokenizer. It is available in full-featured text engines. E.g. based on Apache Lucene: ElasticSearch, Solr, Mongo Atlas, etc.
If your database is relatively small and weights are not essential, you can use regexp:
db.contributors.find({
"$or": [
{
displayname: {
$regex: "oct",
$options: "i"
}
},
{
first_name: {
$regex: "oct",
$options: "i"
}
},
{
last_mname: {
$regex: "oct",
$options: "i"
}
}
]
})
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.
I have two collection:
// Profile
{
_id: "12345",
name: "max",
country: "IT"
}
// Association
{
_id: "43234",
idclub: "1000",
state: "0"
}
I want to insert a Profile on Association without searching it.
In my code i search for an Association but i don't have the object Profile in that moment, i just have its "id".
Is it possible to perform some kind of insert on collection A retrieving on the fly the object of collection B given it's own ID?
And then, is this a recurring practice? As i can find nothing it seems not properly the best way...
Thanks
Use findAndModify operator
db.createCollection("Association");
db.Association.insert({ _id : "43234", idclub:"1000",state:"0"});
db.Association.findAndModify({
query:{ _id:"43234" },
update:{ $set:{ "profile":{ _id:"12345","name":"max","country":"IT" } } }
});
db.Association.find();
{"_id" : "43234", "idclub" : "1000", "state" : "0", "profile" : { "_id" :
"12345", "name" : "max", "country" : "IT" } }
I am stuck here to write mongoose schema for happenings and birthdays fields. I am using mongodb/mongoose and would like to save the similar contents in events collections.
{
"_id" : ObjectId("5938fc171dfe0f225902d85d"),
"month" : 6,
"date" : 9,
"happenings" : [
{
"incident" : "Muhammad, the founder of Islam and unifier of Arabia, died.",
"year" : "632"
},
{
"incident" : "The Army of the Potomac defeats Confederate forces at Battle of Cross Keys, Virginia..",
"year" : "1862"
},
{
"incident" : "Israeli airplanes attack the USS Liberty, a surveillance ship, in the Mediterranean, killing 34 Navy crewmen..",
"year" : "1967"
},
{
"incident" : "Gemini astronaut Gene Cernan attempts to become the first man to orbit the Earth untethered to a space capsule, but is unable to when he exhausts himself fitting into his rocket pack.",
"year" : "1966"
}
],
"birthdays" : {
"actor" : {
"name" : "Josh Pence",
"yob" : 1982,
"birthplace" : "Santa Monica, CA",
"role" : "MOVIE ACTOR",
"image" : "josh_1982.png"
},
"actress" : {
"name" : "Julianna Margulies",
"yob" : 1966,
"birthplace" : "Spring Valley, NY",
"role" : "TV ACTRESS",
"image" : "julianna_1966.png"
},
"player" : {
"name" : "Julianna Margulies",
"yob" : 1987,
"birthplace" : "Ohio",
"role" : "FOOT BALL",
"image" : "julianna_1966.png"
}
}
}
The schema I tried
var schema = new Schema({
day: Number,
Month: Number,
birthdays: Schema.Types.Mixed,
happenings: [],
incident: [String],
year: [Number],
})
var event= mongoose.model('Event', schema);
How should I modify the above schema??
According to your document I think your schema could be like
var schema = new Schema({
day: Number,
Month: Number,
birthdays: Schema.Types.Mixed,
happenings: [{
incident: String,
year: String,
_id: false
}]
});
var event= mongoose.model('Event', schema);
db.employee_details.insert(
on_boarding_id : NumberLong(1),
user_name : String('chandan kumar'),
gender : Timestamp(),
blood_group : String('o+'),
marital_status : String('single'),
pan_no : String('CDSNJHJ8789'),
emergency_contact : Number(98989898989),
mobile_number : Number(9205972503),
hdfc_salary_account_details : Boolean(true),
hdfc_account : String('HJHGHHJ3222423'),
address : [
{
current : [{
address : String('New Nagar Deepatoli'),
pin_code : Number(909990),
city : String('ranchi'),
state : String('jharkhand')
}]
},
{
parament : [{
address : String('Gurgaon iffco chowk'),
pin_code : Number(894893),
city : String('gurgaon'),
state : String('haryna')
}]
}
],
adhaar_no : String('4567HJFGKJGH98')
)
Hi I want to store this data through robomongo UI in mongoDB but it produce error please help me to fix this issue .. thanks for your support.
You forgot to add curly brackets inside insert function.
db.employee_details.insert({
on_boarding_id: NumberLong(1),
user_name: String('chandan kumar'),
gender: Timestamp(),
blood_group: String('o+'),
marital_status: String('single'),
pan_no: String('CDSNJHJ8789'),
emergency_contact: Number(98989898989),
mobile_number: Number(9205972503),
hdfc_salary_account_details: Boolean(true),
hdfc_account: String('HJHGHHJ3222423'),
address: [{
current: [{
address: String('New Nagar Deepatoli'),
pin_code: Number(909990),
city: String('ranchi'),
state: String('jharkhand')
}]
},
{
parament: [{
address: String('Gurgaon iffco chowk'),
pin_code: Number(894893),
city: String('gurgaon'),
state: String('haryna')
}]
}
],
adhaar_no: String('4567HJFGKJGH98')
})