How can we rename a field or give alias to field in MongoDB Atlas charts? - mongodb

How can we rename a field or give alias to field in MongoDB Atlas charts?

Examples:
this is the students collection
{
"_id": 1,
"alias": [ "The American Cincinnatus", "The American Fabius" ],
"mobile": "555-555-5555",
"nmae": { "first" : "george", "last" : "washington" }
},
{
"_id": 2,
"alias": [ "My dearest friend" ],
"mobile": "222-222-2222",
"nmae": { "first" : "abigail", "last" : "adams" }
}
Here I update the nmae field to name
db.students.updateMany( {}, { $rename: { "nmae": "name" } } )
{
"_id": 1,
"alias": [ "The American Cincinnatus", "The American Fabius" ],
"mobile": "555-555-5555",
"name": { "first" : "george", "last" : "washington" }
},
{
"_id" : 2,
"alias" : [ "My dearest friend" ],
"mobile" : "222-222-2222",
"name" : { "first" : "abigail", "last" : "adams" }
}
ref: https://docs.mongodb.com/manual/reference/operator/update/rename/

Related

Getting an array out of the input using aggregate

My input file looks like this:
[
{
"type" : "asdf",
"properties" : {
"Name" : "First center",
"Code" : "ABCD",
"Address" : "Emmastr 14",
"City" : "Rotterdam",
"Postcode" : 55968,
}
},
{
"type" : "qwer",
"properties" : {
"Name" : "Second center",
"Code" : "OTHER",
"Address" : "Havenstraat 15",
"City" : "Rotterdam",
"Postcode" : 88767,
}
},
{
"type" : "zxcv",
"properties" : {
"Name" : "Third center",
"Code" : "ABCD",
"Address" : "Kerkstraat 16",
"City" : "Amsterdam",
"Postcode" : 33948,
}
},
{
"type" : "tyiu",
"properties" : {
"Name" : "Fourth center",
"Code" : "ABCD",
"Address" : "Zeestraat 17",
"City" : "Amsterdam",
"Postcode" : 56475,
}
}
]
I've been tasked to present this information grouped per city (a document for each city).
Only the items that have Code="ABCD" should appear in the output.
Output should be ordered by city name (_id).
Output should be written to a new collection.
So the output I'm looking for is something like this:
_id: "Amsterdam",
center: [
{"Name": "Third center" , "Postcode": 33948, "Address": "Kerkstraat 16"},
{"Name": "Fourth center" , "Postcode": 56475, "Address": "Zeestraat 17"}
]
_id: "Rotterdam",
center: [
{"Name": "First center" , "Postcode": 55968, "Address": "Emmastr 14"}
]
This little snippet filter by "ABCD", groups by city and writes the output to a new collection.
db.centers.aggregate ([
{$match: {"properties.Code": "ABCD"}}
,{ $group: {_id: "$properties.City"}}
,{ $out: "newColl"}
])
But I'm not getting much further because of lack of hands on experience.
I struggle getting an array out of something that's not an array in the input. Is there anyone that could help?
$push to make array of required fields
$sort by _id in ascending order
db.centers.aggregate([
{ $match: { "properties.Code": "ABCD" } },
{
$group: {
_id: "$properties.City",
center: {
$push: {
Name: "$properties.Name",
Postcode: "$properties.Postcode",
Address: "$properties.Address"
}
}
}
},
{ $sort: { _id: 1 } },
{ $out: "newColl" }
])
Playground

How to correct document validation fail in Mongodb?

Ive created the following collection(the creation of which is successful)
db.createCollection("Company", { "validator": { "$jsonSchema": {
"bsonType":"object",
"required":["city_name","city","street_name","building_number","budget","Department"],
"properties":{ "city_name":{ "bsonType":"string",
"description":"name of city" },
"city":{ "bsonType":"string",
"description":"City" },
"street_name":{ "bsonType":"string",
"description" :"name of street" },
"building_number":{"bsonType":"int",
"description":"number of building", minimum: 0, maximum: 500},
"budget":{"bsonType":"double",
"description":"budget of company",minimum: 0 },
"Department":{ "bsonType":"object",
"required":["Department_name","floor_number","Employee"],
"properties":{ "Department_name":{"bsonType":"string",
"description": "name of department" },
"floor_number":{"bsonType":"int",
"description":"number of floor" },
}},
"Employee":{ "bsonType":"object",
"required":["first_name","last_name","DOB","Salary"],
"properties":{"first_name":{"bsonType":"string",
"description":"Employees first name"},
"last_name":{"bsonType":"string",
"description":"Employees last name"},
"DOB":{"bsonType":"date",
"description":"Date of birth of empployee"},
"Salary":{"bsonType":"double",
"description":"Salary of Employee",minimum: 0},
"Position":{"bsonType":"string",
"description":"Position of employee. Field is not required"}}}}}}});
Ive created a set of data to insert into this collection to test the validations
db.Company.insert(
{ "city_name":"Sydney",
"city":"Sydney",
"street_name":"Pitt Street",
"building_number":100,
"budget": 100000.0,
"Department":{"department_name":"Google",
"floor_number":4,
"Employee" :{"first_name" : "George",
"last_name": "Martin",
"DOB": new Date('Dec 26,1981'),
"Salary" : "70000",
"Position": "CEO"}}
});
However when i run this script i get an error
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
Sadly Mongodb isnt very specific in what causes such errors and ive gone through my syntax and declarations and could not pick up on any errors myself,when clearly there is!
Why am i recieving this error when running my code? Thankyou
Try this:
01) Schema:
db.createCollection(
"Company",
{
"validator": {
"$jsonSchema": {
"bsonType":"object",
"required":["city_name","city","street_name","building_number","budget","Department"],
"properties": {
"city_name":{ "bsonType" : "string", "description" : "name of city" },
"city":{ "bsonType" : "string", "description" : "City" },
"street_name":{ "bsonType" : "string","description" : "name of street" },
"building_number": { "bsonType" : "int", "description" : "number of building", minimum: 0, maximum: 500},
"budget": { "bsonType" : "double", "description" : "budget of company",minimum: 0 },
"Department": {
"bsonType":"object",
"required":["Department_name","floor_number","Employee"],
"properties": {
"Department_name":{"bsonType":"string", "description": "name of department" },
"floor_number":{"bsonType":"int", "description":"number of floor" },
"Employee":{
"bsonType":"object",
"required":["first_name","last_name","DOB","Salary"],
"properties":{
"first_name":{"bsonType":"string", "description":"Employees first name"},
"last_name":{"bsonType":"string", "description":"Employees last name"},
"DOB":{"bsonType":"date", "description":"Date of birth of empployee"},
"Salary":{"bsonType":"double", "description":"Salary of Employee",minimum: 0},
"Position":{"bsonType":"string", "description":"Position of employee. Field is not required"}
}
}
}
},
}
}
}
}
);
02) Insert:
db.Company.insert(
{
"city_name": "Sydney",
"city": "Sydney",
"street_name": "Pitt Street",
"building_number": NumberInt(100),
"budget": 100000.0,
"Department":{
"Department_name":"Google",
"floor_number": NumberInt(4),
"Employee" : {
"first_name" : "George",
"last_name": "Martin",
"DOB": new Date('Dec 26,1981'),
"Salary" : 70000.0,
"Position": "CEO"
}
},
});
I have to do a few changes:
'int' fields have to be NumberInt(number) in the insert command.
The scheme has been changed so that 'Employee' is within 'Department'.
Salary must be double.
"Salary" : "70000" is an int, but the schema ask for double: "Salary":{"bsonType":"double", "description":"Salary of Employee",minimum: 0},.
I would recommend that you use the alias "bsonType":"number" in your schema instead of int,double, long, decimal. Since javascript is not typed, it can be a real pain to keep track which is used in your code.
See doc: https://docs.mongodb.com/manual/reference/operator/query/type/#available-types

Querying, projecting and sorting multiple fields of documents inside a mongoDB collection

I have a simple mongoDB collection, named usersCollection, whose generale structure is this:
[
{
"username" : "john",
"sex" : "m",
"email" : "john#gmail.com",
"courses" : [
{
"title" : "medicine",
"grade": 25,
},
{
"title" : "art",
"grade": 29,
},
{
"title" : "history",
"grade": 21,
}
]
},
{
"username" : "jane",
"sex" : "f",
"email" : "jane#gmail.com",
"courses" : [
{
"title" : "math",
"grade": 20,
},
{
"title" : "medicine",
"grade": 30,
}
]
},
{
"username" : "sarah",
"sex" : "f",
"email" : "sarah#gmail.com",
"courses" : [ ]
},
{
"username" : "josh",
"sex" : "f",
"email" : "josh#gmail.com",
"courses" : [
{
"title" : "english",
"grade": 28,
}
]
},
{
"username" : "mark",
"sex" : "m",
"email" : "mark#gmail.com",
"courses" : [
{
"title" : "history",
"grade": 30,
},
{
"title" : "medicine",
"grade": 19,
},
{
"title" : "math",
"grade": 22,
}
]
}
]
Every user is a member of usersCollection and has some general informations and a list of courses that he/she has already completed with the relative grades.
Can anyone tell me how I can query usersCollection to get a descending sorted array that contains an object for all users that have already completed a specific course? Every object of this array should contains the "name", the "email" and the "grade" of the relative user.
For example, launching a query on usersCollection around the course with name "medicine", I would obtain this array:
[
{
"username": "jane",
"email": "jane#gmail.com",
"grade": 30
},
{
"username": "john",
"email": "john#gmail.com",
"grade": 25
},
{
"username": "mark",
"email": "mark#gmail.com",
"grade": 19
}
]
You can manage to do it using sort and group pipeline of mongoDB.
if you want to get any specific courses you can apply match pipeline before sort pipeline.
db.users.aggregate([
{
$unwind: "$courses"
},
{
$match: {
'courses.title': 'medicine'
}
},
{
$sort: {
'courses.title': -1,
'courses.grade': -1,
}
},
{
$group: {
_id: "$courses.title",
records: {
$push: {
"_id" : "$_id",
"username" : "$username",
"sex" : "$sex",
"email" : "$email",
"grade":"$courses.grade"
}
}
}
}
])

How to change the response in MongoDB using translatable fields

I am looking for the way how to resolve this and I can't find it. I appreciate your help.
I have a collection with products like:
[
{
"name": [
{ "es": "Producto 1" },
{ "en": "Product 1" }
]
"reference": "PR1",
"price": "20",
"description": [
{ "es": "Descripción 1" },
{ "en": "Description 1" }
]
}
]
And I would like to do:
db.products.aggregate(); // Find by language es for example:
And get:
[
{
"name": "Producto 1",
"reference": "PR1",
"price": "20",
"description": "Descripción 1"
}
]
Thanks very much.
I would suggest a schema change though to this:
[
{
"name" : [
{
"language" : "es",
"description" : "Producto 1"
},
{
"language" : "en",
"description" : "Product 1"
}
],
"reference" : "PR1",
"price" : "20",
"description" : [
{
"language" : "es",
"description" : "Descripción 1"
},
{
"language" : "en",
"description" : "Description 1"
}
]
}
]
cause then you could actually group by the language in your case.
If this is possible then you could do the following:
db.products.aggregate([
{$unwind: "$someName"},
{$unwind: "$someName.name"},
{$unwind: "$someName.description"},
{
$group: {
_id: {namelang: "$someName.name.language", namedesc: "$someName.description.language"},
name: {$first: "$someName.name.description"},
reference: {$first: "$someName.reference"},
price: {$first: "$someName.price"},
description: {$first: "$someName.description.description"}
}
},
{
$match: {
"_id.namelang": "en",
"_id.namedesc": "en"
}
}
])
FYI since you didn't provided your complete json I created one random. Here is the complete schema:
{
"_id" : ObjectId("59ea07a600f5db2660dbf162"),
"someName" : [
{
"name" : [
{
"language" : "es",
"description" : "Producto 1"
},
{
"language" : "en",
"description" : "Product 1"
}
],
"reference" : "PR1",
"price" : "20",
"description" : [
{
"language" : "es",
"description" : "Descripción 1"
},
{
"language" : "en",
"description" : "Description 1"
}
]
}
]
}

mongodb find element in array or less but no other

I have this collection:
{
"title": "First Item",
"attributes": [
{
"id": "1",
"text": "Alpha"
},
{
"id": "2",
"text": "Bravo"
},
{
"id": "3",
"text": "Charlie"
}
]
},
{
"title": "Second Item",
"attributes": [
{
"id": "1",
"text": "Alpha"
},
{
"id": "2",
"text": "Bravo"
},
{
"id": "3",
"text": "Tango"
}
]
}
Trying search with these values for "attributes.text" field:
{ "Alpha", "Bravo", "Charlie", "Delta" }
I want to find only "First Item" document that contains at least these keys but no others.
But trying these values:
{ "Alpha", "Bravo", "Delta" }
or
{ "Alpha", "Bravo" }
I do not want to find any result (beacuse "Charlie" is missing).
Thank you
Use the $in operator to match values in the attributes object array. The following query will select all documents in the collection where the text field value of the attribute object array is either "Alpha", "Bravo" or "Delta":
dbo.collection.find({
"attributes.text": {
"$in": ["Alpha", "Bravo", "Delta"]
}
});
This will return the two documents:
/* 0 */
{
"_id" : ObjectId("551187bae3757367bf8bd915"),
"title" : "First Item",
"attributes" : [
{
"id" : "1",
"text" : "Alpha"
},
{
"id" : "2",
"text" : "Bravo"
},
{
"id" : "3",
"text" : "Charlie"
}
]
}
/* 1 */
{
"_id" : ObjectId("551187bae3757367bf8bd916"),
"title" : "Second Item",
"attributes" : [
{
"id" : "1",
"text" : "Alpha"
},
{
"id" : "2",
"text" : "Bravo"
},
{
"id" : "3",
"text" : "Tango"
}
]
}