I can do a find in mongodb like:
db.user.find({ "show": true}, { firstname: 1, lastname: 1, email:1 })
Now I'd like to be a little more specific to let people hide their email address.
So what I'd like is to query if "show":true then get firstname:1, lastname:1 AND (email:1 iff show_email:true)
worst case I can take all the info and filter it out on the back end with a map function but I wondered if there was a nice query-able way??
The truthiness of the projection object's fields are all that matter, so you can just do it as:
db.user.find({ "show": true }, { firstname: 1, lastname: 1, email: show_email })
Since you didnt specify any driver specification, I am betting on this, the MongoShell
if(show_email){
db.user.find({ "show": true}, { firstname: 1, lastname: 1, email:1 })
}
else{
db.user.find({ "show": true}, { firstname: 1, lastname: 1})
}
Related
I am trying to update a property from nested array object. I use this code but not working.
This is my data
[
{
_id: ObjectId("630a869a887d39ef359ef6e6"),
firstName: 'Esra',
lastname: 'Demirci',
age: 33
},
{
_id: ObjectId("630a86a5887d39ef359ef6e7"),
firstName: 'Efe',
lastname: 'Demirci',
age: 7,
history: [ { disease: 'flue', threatment: 'given serum' } ]
},
{
_id: ObjectId("630a8e10887d39ef359ef6e8"),
firstName: 'Ali',
lastname: 'Demirci',
age: 34,
history: [
{ disease: 'cold', threatment: 'medicine given' },
{ disease: 'alergy', threatment: 'refered alergy department' }
]
}
]
This is my query in mongodb
db.patientData.update({"history.disease":"cold"},{$set:{"history.disease":"ali updated this one"}})
I wanna update data which has disease:"cold" value to new value.
Try using the $ sign when updating in MongoDB, like so:
db.patientData.update({"history.disease":"cold"},{$set:{"history.$.disease":"ali updated this one"}})
well...
I have a collection of users, one user looks like
{ userId: "someId", fullName: "AnyName", email: "anyEmail#mail.com"}
and of course Mongo adds one _id
all fine here, but a have an express server and I receive and array of existing users with a POST.
[
{ userId: "123", fullName: "name1 EDITED", email: "anyEmail1#mail.com"},
{ userId: "124", fullName: "name2 EDITED", email: "anyEmail2#mail.com"},
{ userId: "125", fullName: "name3 EDITED", email: "anyEmail3#mail.com"},
{ userId: "126", fullName: "name4 EDITED", email: "anyEmail4#mail.com"}
]
I want edit the existing user with the news values receive in the array but I don't know if I have to iterate and update each document or if I can pass the array of users to update all of them with a single query.
similar to what "insertMany" method does
I'm trying to implement a user search that looks into the user's given names and their username, while also being able to sort results by relevance.
I tried creating a text index like this
db.users.createIndex({
username: 'text',
firstName: 'text',
lastName: 'text'
},
{
name: 'text_search',
default_language: 'en',
language_override: 'language'
})
But this doesn't take into account partial terms, so if I search for "Juan F", I get the following results
{ score: 3.7, username: "juanjo", firstName: "Juan", lastName: "Rivas F" },
{ score: 2.95, username: "Juan.rodriguez", firstName: "Juan", lastName: "Rodriguez" },
{...} // 6 more
{ score: 2.2, lastName: "Fuentes", firstName: "Juan", username: "juanfuentes" }
I understand that text indexes take into account similar words, but not partial terms, so with "Juan Fuente" I get the desired result, with "Juan F", "Juan Fu", etc, I don't.
Is there a way to improve this, in order to be able to implement a search that returns results as the user types into a search box?
Edit This is the query I tried:
db.users.find(
{ $text: { $search: "juan f" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
I have a collection of case with a field named status (integer) whose valid values are 0, 1, 2, 4 and 8, representing "New", "WIP", "Solved", "Canceled" and "Closed" respectively.
So, in mongoose syntax, it might be like:
const caseSchema = new Schema({
createdOn: Date,
subittedBy: String,
status: Number,
...
});
const statusSchema = new Schema({
value: Number,
description: String
});
Is this a good way to organize the data? How do I make a query to retrieve cases with the status field properly filled with the description?
It is one way to do it sure. You could do the query by using $lookup. It would look something like this:
db.getCollection('<YourCasesColName>').aggregate([
{ $match : { 'status' : 1 } }, // or { $in: [1,2,3] },
{
$lookup: {
from: '<YourStatusColName>',
localField: 'status',
foreignField: 'value',
as: 'statusDoc',
}
}
])
Another way is to add a reference to the actual status via ObjectId so that instead of numbers in the cases you would be storing references to the actual Status objects and in this way have a better referential integrity. However you would still need to do similar query to get both in one shot. So here is what I am talking about:
const caseSchema = new Schema({
createdOn: Date,
subittedBy: String,
status: { type: mongoose.Schema.Types.ObjectId, ref: 'Status' },
// ^ now your status hows reference to exactly the type of status it has
});
const statusSchema = new Schema({
value: Number,
description: String
});
So the actual data would look like this:
// Statuses
[{
_id: <StatusMongoObjectID_1>,
value: 1,
description: 'New'
},{
_id: <StatusMongoObjectID_2>,
value: 2,
description: 'New'
}]
// Cases
[{
_id: <MongoObjectID>,
createdOn: '<SomeISODate>',
subittedBy: '<SomeString>',
status: <StatusMongoObjectID_1>
},
{
_id: <MongoObjectID>,
createdOn: '<SomeISODate>',
subittedBy: '<SomeString>',
status: <StatusMongoObjectID_2>
}]
I have a collection with documents like this:
{
_id: af3F3afafaa,
firstName: "John",
family: [{name: "David", relation: "brother", alive: true},
{name: "Susan", relation: "mother", alive: false}]
}
Is there a way to write a publication that hides a field in the family field array? So if I subscribed to the publication I would get:
{
_id: af3F3afafaa,
firstName: "John",
family: [{name: "David", alive: true},
{name: "Susan", alive: false"}]
}
According to the Meteor docs, something like this could work:
Meteor.publish('family', function(famId) {
return Families.find(famId, {
fields : {
"family.relation" : 0 //Exclude family.relation from the sent data
}
});
});