I'd like to replace an object in an array using an index, but nothing will save. This is what the document looks like:
{
"_id": {
"$oid": "58a71ec0c80a9a0436ae2fb1"
},
"owner": "contact1#gmail.com",
"contacts": [
{
"work": "",
"home": "",
"mobile": "",
"email": "",
"company": "",
"last": "Contact",
"middle": "",
"first": "New"
},
{
"first": "Another",
"middle": "",
"last": "Contact",
"company": "",
"email": "",
"mobile": "",
"home": "",
"work": ""
}
],
"__v": 1
}
And this is what I've tried..
Contacts.findById({_id: "58a71ec0c80a9a0436ae2fb1"}, function(err,document) {
document.contacts[req.body.indexOfObjectToBeEdited] = req.body.updatedObject
console.log(document)
document.save(function(err) {
return res.json({event:"Updated Contact"})
})
})
Right before document.save() I console.log(document) and it reflects the correct changes. But when I save, nothing is updated in the mongodb and I receive no errors. What should I be doing differently?
try inserting this line right before saving. As modifying an array require we need to manual tell the mongoose the it is modified.
document.markModified("contacts");
Check the Usage Notes in the documentation for more information
http://mongoosejs.com/docs/schematypes.html
Related
I am new to mongodD. Although i have wrote correct logic to push object inside cardsData bankCardsArray, but i am not able to make logic to edit a card.
**I have following Data in MongoDB, **
UserData = {
"_id": "63b43ab32fc8d3c100cafecc",
"name": "Praveen Lohar",
"email": "pr********#gmail.com",
"password": "$2b$12$3nwifHakrBu94BwLXAC4Nu16Kw0.xyW8vAIPTMSgY7cYttVklDIZq",
"loginIdsArray": [
{
"title": "Airtel App",
"logoIndex": 3,
"category": "Finance",
"app": "Airtel Thanks",
"username": "p******#gmail.com ",
"password": "xxxxxxx",
"isFavourite": false,
"_id":"63b440ee738a50fc333df3ca"
}
],
"cardsData": {
"bankCardsArray": [
{
"title": "SBI CC",
"logoIndex": 72,
"category": "Bank",
"cardHolder": "Prsscscs",
"cardNumber": "524xxxxxxxx20xx",
"expiry": "23/54",
"cvv": "00",
"isFavourite": false,
"_id": "63b974adb9acaa24a4ebec8b"
},
{
"title": "AXIS CC",
"logoIndex": 85,
"category": "Bank",
"cardHolder": "blsllslss",
"cardNumber": "524xxxxxxxx20xx",
"expiry": "23/54",
"cvv": "00",
"isFavourite": false,
"_id": "63b974adb9acaa24a4ebe5f"
}
],
"identityCardsArray": [
{
"title": "Aadhar Card",
"logoIndex": 98,
"category": "Identity",
"cardHolder": "Name_1",
"cardNumber": "54*******455454",
"issueDate": "2012",
"dob": "23/05",
"isFavourite": false,
"_id":"63b974e6bd0d03c116955f67"
}
],
"licenseCardsArray": [
{
"title": "Two Wheeler License",
"logoIndex": 0,
"category": "License",
"cardHolder": "Klaus Michealson",
"licenseNumber": "RJ/22/ADL-542/474/01",
"expiry": "2036",
"dob": "13/06",
"isFavourite": false,
"_id":"63b97535bd0d03c116955f69"
}
]
}
}
I want to find the user with _id
Then for that user i want to got to cardsData object
Then in cardsData object i want to got to bankCardsArray
Then in bankCardsArray , i want to update fields of a card with particular id
Const res = findOneAndUpdate(
{ 'cardsData.bankCardsArray._id':card_id },
{ $set{ 'cardsData.bankCardsArray.$.title': req.body.title });
Use "." operator to access nested fields.
Refer these mongodb documentation
query-array-of-documents
query-embedded-documents.
Hope this helps.
There is a sub-field called 'name' in MongoDB Collection (User):
[
{
"teacher": {
"name": "Alex",
"email": "alex#domain.com"
},
"waiter": {
"name": "Feliks",
"email": "feliks#domain.com"
},
"pilot": [
{
"name": "Sam",
"email": "sam#domain.com"
},
{
"name": "alice",
"email": "alice#domain.com"
}
],
},
{
"teacher": {
"name": "max",
"email": "max#domain.com"
},
"waiter": {
"name": "Sam",
"email": "sam#domain.com"
},
"pilot": [
{
"name": "richard",
"email": "richard#domain.com"
},
{
"name": "alice",
"email": "alice#domain.com"
}
],
}
]
How can I find data based on the field 'name'. For example, when I'm looking for 'Sam', it should return me the all documents since 'Sam' is in "waiter" and "pilot" in first and second documents respectively.
I cannot do something like:
User.find({"teacher.name": "Sam", "waiter.name": "Sam", "pilot.name": "Sam" })
This will return me nothing as it is an AND logic. What I need is an OR logic.
You can use the $or operator.
So the query should look like this:
User.find({ $or: [
{ "teacher.name": "Sam" },
{ "waiter.name": "Sam" },
{ "pilot.name": "Sam" }
]
});
Read here for me details.
I have this json schema
"header": {
"self": {},
"items": [
{
"_id": "5ec7e61979ec9914ecefc539",
"title": "Test",
"root": "true",
"alignment": "left",
"page": "test",
"translate": "",
"toggle": "",
"icon": "",
"IsActive": 1,
"submenu": [
{
"_id": "5ece913a353a71309084768d",
"title": "Sub Test",
"bullet": "dot",
"page": "test",
"translate": "MENU.TEST1",
"icon": "flaticon-stes-3",
"IsActive": 1
},
{
"_id": "5ece935d79972f0390997179",
"title": "Sub Test",
"bullet": "dot",
"page": "test",
"translate": "MENU.TEST2",
"icon": "flaticon-stes-3",
"IsActive": 1
}
]
}
]
}
// Index based on a previous query
this.db.collection('AssetData').find({"header.items.$.submenu.[0]._id":ObjectID("5ece913a353a71309084768d"));
//Tried with elemMatch
this.db.collection('AssetData').find(
{
"header.items": {
$elemMatch:{
"submenu": {
$elemMatch:{
"_id":ObjectID("5ece913a353a71309084768d")
}
}
}
}
});
And I am wanting to retrieve one of the sub-menu object data based on the _id from the sub-menu, but I'm having trouble retrieving it.
I'm not sure If I could use an index of the second array from another query to obtain the data, or if there's another way that I'm missing like elem match.
I am using MongoDB 3.5.6.
What would be the best way to retrieve this?
// Index based on a previous query
this.db.collection('AssetData').find({"header.items.$.submenu.[0]._id":ObjectID("5ece913a353a71309084768d")});
//Tried with elemMatch
this.db.collection('AssetData').find(
{
"header.items": {
$elemMatch:{
"submenu": {
$elemMatch:{
"_id":ObjectID("5ece913a353a71309084768d")
}
}
}
}
}).exec(function(err, item) {
console.log(item);
// here you can retrieve the stock from item, as you wish
});
hopefully it will help you
I have some MongoDB documents like that:
{
"group": "P32666",
"order": [{
"_id": {
"$oid": "5e8e9b40e7999f6b90fd88bf"
},
"name": "Dmitriy A",
"login": "example",
"password": "example",
"email": "example",
"level": "user",
"uuid": "b6a19744-bb20-4d39-9e1e-0ca5b464f890"
}, {
"_id": {
"$oid": "5e8ea03f5a21c26b90983de4"
},
"name": "Dmitriy B",
"login": "example",
"password": "example",
"email": "example",
"level": "user",
"uuid": "556924c3-605c-44cc-8a26-d32f58222e89"
}, {
"_id": {
"$oid": "5e8ea0645a21c26b90983de5"
},
"name": "Dmitriy C",
"login": "example",
"password": "example",
"email": "example",
"level": "user",
"uuid": "aef00707-ef00-4ce9-918b-5cef17e7280b"
}]}
I'm working with Mongo in Mongoose and can't understand how to query all documents(like above) where field(array) "order" has at least one object within where field, for example, "login" is queal to "example". How can I do this?
I tried something like this:
export async function getQueues(request: Request, response: Response) {
const returningQueues = await queues.find({order: [login: request.params.login]});
response.json(returningQueues);
But TypeScript error (56 missing properties(mostly internal Mongoose's) of type "User", which I store within an array) says that's I am wrong in my thoughts.
If you just have one condition on the array field, you can simply do:
queues.find({"order.login": request.params.login})
But if you have multiple conditions, you can use $elemMatch:
queues.find({
order: { $elemMatch: { login: request.params.login, name: request.params.name } }
})
In our application we obtain the field values as columns using Spark sql. Im' trying to figure out how to put the columns values to nested json object and push to Elasticsearch. Also is there a way to parameterise values in selectExpr to pass to the regex?
We are currently using the Spark Java API.
Dataset<Row> data = rowExtracted.selectExpr("split(value,\"[|]\")[0] as channelId",
"split(value,\"[|]\")[1] as country",
"split(value,\"[|]\")[2] as product",
"split(value,\"[|]\")[3] as sourceId",
"split(value,\"[|]\")[4] as systemId",
"split(value,\"[|]\")[5] as destinationId",
"split(value,\"[|]\")[6] as batchId",
"split(value,\"[|]\")[7] as orgId",
"split(value,\"[|]\")[8] as businessId",
"split(value,\"[|]\")[9] as orgAccountId",
"split(value,\"[|]\")[10] as orgBankCode",
"split(value,\"[|]\")[11] as beneAccountId",
"split(value,\"[|]\")[12] as beneBankId",
"split(value,\"[|]\")[13] as currencyCode",
"split(value,\"[|]\")[14] as amount",
"split(value,\"[|]\")[15] as processingDate",
"split(value,\"[|]\")[16] as status",
"split(value,\"[|]\")[17] as rejectCode",
"split(value,\"[|]\")[18] as stageId",
"split(value,\"[|]\")[19] as stageStatus",
"split(value,\"[|]\")[20] as stageUpdatedTime",
"split(value,\"[|]\")[21] as receivedTime",
"split(value,\"[|]\")[22] as sendTime"
);
StreamingQuery query = data.writeStream()
.outputMode(OutputMode.Append()).format("es").option("checkpointLocation", "C:\\checkpoint")
.start("spark_index/doc")
Actual output:
{
"_index": "spark_index",
"_type": "doc",
"_id": "test123",
"_version": 1,
"_score": 1,
"_source": {
"channelId": "test",
"country": "SG",
"product": "test",
"sourceId": "",
"systemId": "test123",
"destinationId": "",
"batchId": "",
"orgId": "test",
"businessId": "test",
"orgAccountId": "test",
"orgBankCode": "",
"beneAccountId": "test",
"beneBankId": "test",
"currencyCode": "SGD",
"amount": "53.0000",
"processingDate": "",
"status": "Pending",
"rejectCode": "test",
"stageId": "123",
"stageStatus": "Comment",
"stageUpdatedTime": "2019-08-05 18:11:05.999000",
"receivedTime": "2019-08-05 18:10:12.701000",
"sendTime": "2019-08-05 18:11:06.003000"
}
}
We need the above columns under a node "txn_summary" such as the below json:
Expected output:
{
"_index": "spark_index",
"_type": "doc",
"_id": "test123",
"_version": 1,
"_score": 1,
"_source": {
"txn_summary": {
"channelId": "test",
"country": "SG",
"product": "test",
"sourceId": "",
"systemId": "test123",
"destinationId": "",
"batchId": "",
"orgId": "test",
"businessId": "test",
"orgAccountId": "test",
"orgBankCode": "",
"beneAccountId": "test",
"beneBankId": "test",
"currencyCode": "SGD",
"amount": "53.0000",
"processingDate": "",
"status": "Pending",
"rejectCode": "test",
"stageId": "123",
"stageStatus": "Comment",
"stageUpdatedTime": "2019-08-05 18:11:05.999000",
"receivedTime": "2019-08-05 18:10:12.701000",
"sendTime": "2019-08-05 18:11:06.003000"
}
}
}
Adding all columns to a top level struct should give the expected output. In Scala:
import org.apache.spark.sql.functions._
data.select(struct(data.columns:_*).as("txn_summary"))
In Java I would suspect it it would be:
import org.apache.spark.sql.functions.struct;
data.select(struct(data.columns()).as("txn_summary"));