getting array values ruby - arrays

I have an array which is result of a query.
r = [
#<Reservation id: 27, schedule_id: 1, name: "test user", gender: "no_answer",
reservation_num: 1, zip: "", prefecture: "", address: "", street: "",
tel: "", note: "", satisfied: true, canceled: false, seq: 27,
created_at: "2019-08-28 06:04:30", updated_at: "2019-08-28 06:04:30",
created_by: 2, updated_by: 2, from_partner: false, no_counting: false,
reservation_time: nil, one_day_payment: nil, payment_id: 123456>
]
I want to get the payment_id but don't understand how should I write.

If you have number of records in array, you can get payment_id in form of array as below,
r.map(&:payment_id)

Looks like you should be able to select the first reservation from that array and then call on the payment_id. Like:
r.first.payment_id

To get all payment_id's you can do
r.map(&:payment_id)

You can also use the collect method
r.collect(&:name)

You can pluck payment ids (from the required set of data) with the following :
Reservation.pluck(:payment_id)

Related

Picking a random element from Swift Class

This is a model of my makeshift database
var categories: [Category] = [
Category(name: "X",
sign: [Sign(code: "X-1", name: "***", description: "", picture: ""),
Sign(code: "X-2", name: "***", description: "", picture: "")]),
Category(name: "Y",
sign: [Sign(code: "Y-1", name: "Yyy", description: "", picture: ""),
Sign(code: "Y-2", name: "yyy", description: "", picture: "")]),
Category(name: "Z",
sign: [Sign(code: "Z-1", name: "Zzz", description: "", picture: ""),
Sign(code: "Z-2", name: "ZZZ", description: "", picture: "")])
]
I need to get one random element of any category (not one from each) from this base and print it as sign.code
I prepared the variable to store the value:
var RandomSign: Sign
And tried to do it with for loop:
func randomSign() {
for categorie in categories {
randomSign = categorie.sign.randomElement()
But, in the result, my loop generate me random element from each category, and finally save only random from the last one. I would like print for example "X-2" in my consol as random selected value.
Why not pick a random category and then a random sign from that random category?
func randomSign() {
randomSign = categories.randomElement()!.sign.randomElement()!
}
This code will crash if any of the arrays are empty. It would be safer if randomSign was optional then you can do:
func randomSign() {
randomSign = categories.randomElement()?.sign.randomElement()
}
Or you could fallback to a default Sign:
func randomSign() {
randomSign = categories.randomElement()?.sign.randomElement() ?? Sign(code: "empty", name: "***", description: "", picture: "")
}

retrieve all data by size of array in spring mongo template

Suppose I have these:
{id: 1, name: name1, tags: [{id: 1, name: tag1}]},
{id: 2, name: name2, tags: []},
{id: 3, name: name3, tags: [{id: 3, name: tag3}, {id:33, name: tag33}]},
{id: 4, name: name4}
Then execute a query and I want this:
{id: 1, name: name1, tags: [{id: 1, name: tag1}]},
{id: 3, name: name3, tags: [{id: 3, name: tag3}, {id:33, name: tag33}]}
Getting documents that have "tags" array and its size is larger than 0. But don't know how to create my criteria.
I tried this but throws an error saying that size() has to take an argument of int...
where(tags).size().gt(0)
Anyone knows the correct one?
'$size' operator doesn't accept the range parameters. You could use positional value existence to decide the size. as follows
db.collection.find({
"tags.0": {
$exists: true
}
})
In Spring, You could try as follows,
mongoTemplate.find(Query.query(Criteria.where("tags.0").exists(true)));
You can use $not operator:
where("tags").not().size(0).andOperator(where("tags").exists(true));
db.collection.find({
"tags": {
"$not": {
"$size": 0
}
},
"$and": [
{
"tags": {
"$exists": true
}
}
]
})
Alternative: You cannot create this with Spring-data-mongo framework:
db.collection.find({
tags: {
$exists: true,
$not: {
$size: 0
}
}
})

How to change value of JSON property in angular

I have array of items. inside that i have objects
Please find the structure of one JSON object.
[{ApprovedBy: ""
ApprovedDate: "10/12/2019 7:27:24 AM"
AssignedTo: null
ChildClashes: [{_ClashPoint: {X: "0", Y: "0", Z: "0"},…}, {_ClashPoint: {X: "0", Y: "0", Z: "0"},…},…]
ClashFoundDate: "9/12/2019 7:27:24 AM"
ClashID: "109d3ee3-d470-4534-ac72-0b4f2c3c90eb"
ClashImage: null
ClashName: "New Group"
ClashPublishedBy: "Srini"
ClashStatus: "Reviewed"
Comments: null
Description: "Hard"
Distance: "-2.5"
GroupID: null
ID: 456
ImagePath: null
IsGroup: true
Item1: null
Item2: null
RevisionID: "1"
Viewpoint: ""},
........]
so i want to change the format of approveddate and clashfounddate to dates with MM/dd/YYYY format.
Please let me know how to do it.
please reduce the for loops as much as possible.
thanks in advance.
Inject date pipe in construtor like
constructor(
private datePipe:DatePipe
)
and then
yourdata.forEach(d=>{
d.ClashFoundDate=this.datePipe.transform(d.ClashFoundDate,'MM/dd/yyyy')
d.ApprovedDate=this.datePipe.transform(d.ApprovedDate,'MM/dd/yyyy')
})
date pipe demo

MongoDB - Can't push an item to an array inside an object inside an array

I have this object in MongoDB:
{
_id: ObjectId("1"),
data: {
city: "ccp",
universities: [
{
_id: "2"
name: "universityOne"
students: []
},
{
_id: "3"
name: "universityTwo",
students: []
}
]
}
}
I need to push a Student object inside the students array inside the universityOne object inside the universities array, inside the global object.
I tried documentation and come up with this queries.
Mongo shell returns { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }. And nothing changes.
Here are the queries formatted/unformatted, so you can see them:
db.pautas.updateOne({_id: ObjectId("1")}, {$push: {"data.universities.$[id].students": {name: "aStudentName", age: 22}}}, {arrayFilters: [{"id._id": ObjectId("2")}]})
db.pautas.updateOne({_id: ObjectId("1")}, {$push: {"data.universities.$[id].students": {name: "aStudentName", age: 22}}}, {arrayFilters: [{"id._id": ObjectId("2")}]})
This second query is with the name of the university on the mongo [<identifier>]. But doesn't work either.
db.pautas.updateOne({_id: ObjectId("1")}, {$push: {"data.universities.$[name].students": {name: "aStudentName", age: 22}}}, {arrayFilters: [{"name.name": "universityOne"}]})
db.pautas.updateOne({_id: ObjectId("1")}, {$push: {"data.universities.$[name].students": {name: "aStudentName", age: 22}}}, {arrayFilters: [{"name.name": "universityOne"}]})
Regards.
UPDATE
Real object:
{
_id: ObjectId("5c6aef9bfc1a2693588827d9"),
datosAcademicos: {
internados: [
{
_id: ObjectId("5c6bfae98857df9f668ff2eb"),
pautas: []
},
{
_id: ObjectId("5c6c140f8857df9f668ff2ec"),
pautas: []
}
]
}
}
I need to add a Pauta to the pautas array. I've set pautas to an array of strings for debugging purpose, so just need to push a "hello world" or whatever string.
I tried this with the answers I've been given:
db.pautas.updateOne({"_id":ObjectId("5c6aef9bfc1a2693588827d9"), "datosAcademicos.internados._id": ObjectId("5c6bfae98857df9f668ff2eb")}, { $push: {"datosAcademicos.internados.$.pautas": "hi"}})
db.pautas.updateOne({"_id":ObjectId("5c6aef9bfc1a2693588827d9"), "datosAcademicos.internados._id": ObjectId("5c6bfae98857df9f668ff2eb")}, { $push: {"datosAcademicos.internados.$.pautas": "hi"}})
Update 2:
Mongo version: v4.0.2
Using Robo 3T.
I created a test database
And tried this command
Still not working.
There are 3 issues with your statement. First, the root ID field is "id" and you're querying the "_ID".
Second, you should put the match fields altogether. This update works as expected.
Third, you should use "$" to select the nested array position, not "$[id]".
db.pautas.updateOne(
{ "id": ObjectId("1"), "data.universities._id": "2"},
{$push:
{"data.universities.$.students": {name: "aStudentName", age: 22}}
})
Answer to the question UPDATE:
The update statement worked just fine.
Update statement
Record after update - I ran my update with your data and then the update code you posted, both worked just fine.

Mongoid find_and_modify deprecated

I'm currently updating a Rails app to Mongoid 5. I've having trouble updating some code that uses a deprecated method (find_and_modify). Any help would be appreciated.
In Mongoid 4, I have this method to find and upsert:
LineItem.where({
date: Date.today,
location: "Location",
department: "Department"
}).find_and_modify({
"$set" => {
hours: 8,
updated_at: Time.current
},
"$setOnInsert" => {
account_id: ObjectId("5739f4534f4e48b2aa00091c"),
date: Date.today,
location: "Location",
department: "Department",
created_at: Time.current
}
}, upsert: true)
What is the equivalent using Mongoid 5?
Thanks.
From this changelog:
find_and_modify has been removed and replaced with 3 options: find_one_and_update,
find_one_and_delete and find_one_and_replace.

Resources