Insert object in nested array mongodb nodejs - arrays

So I am trying to insert an object in parameters and have been unsuccessful. My mongodb structure looks like this:
[
{
"_id": "04",
"name": "test service 4",
"id": "04",
"version": "0.0.1",
"title": "testing",
"description": "test",
"protocol": "test",
"operations": [
{
"_id": "99",
"oName": "test op 52222222222",
"sid": "04",
"name": "test op 52222222222",
"oid": "99",
"parameters": {},
"description": "testing",
"returntype": "test"
},
{
"_id": "58",
"oName": "test op 52222222222",
"sid": "04",
"name": "test op 52222222222",
"oid": "58",
"parameters": {},
"description": "testing",
"returntype": "test"
}
]
}
]
I want to be able to add an object into parameters with basic details such as name, id, and type. I am not entirely sure how to tackle this as I have all other CRUD operations implemented up until the parameters part. How should I go about to complete this? I know mongodb has issues when trying to insert something into an array inside an array, so if anyone has any suggestions as to how I can complete this I would really appreciate it. Thanks.
One of the problems is I do not have access to the _id of the root object, but I do have the _id for the operation where I am inserting the parameter. Hence I was trying to insert the parameter using this code:
collection.update({"operations":{"$elemMatch": {"oid": oid}}}, {'$addToSet':{"operations.parameters": {name: "test"} }}, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(result[0]);
}
});
This does not work though.

I was able to complete the insert by using the following code:
collection.update({ "operations": {$elemMatch: {_id:oid}}}, {$addToSet: { "operations.$.parameters" : parameter}}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(result[0]);
}
});
Just in case anyone needed it.

This is because you need to use positional operator, The example I am copying from the link is almost the same as in your case:
db.students.update(
{ _id: 4, "grades.grade": 85 },
{ $set: { "grades.$.std" : 6 } }
)

Related

How to update array inside MongoDB document

Can someone help me with a solution to update an array object inside the MongoDB document, I've tried a couple of methods but still it's to updating, here is my document that I want to update the array in the document.
{
"title": "Products",
"description": "test",
"image": "bdd8510d75f6e83ad308d5f306afccef_image.jpg",
"_created_at": "2021-06-07T20:51:08.316Z",
"ratingCount": 0,
"ratingTotal": 0,
"placeListSave": [
{
"objectId": "g70brr45pfi",
"name": "Kale",
"email": "null",
"strBrandLogo": "84de8865e3223d1ca61386355895aa04_image.jpg",
"storeNumber": "56",
"phone": "0815342119",
"createdAt": "2021-06-10T10:19:53.384Z",
"image": "ad1fb7602c2188223fd891a52373cb9d_image.jpg"
},
{
"objectId": "0qokn33p773",
"name": "Apple",
"email": null,
"strBrandLogo": null,
"storeNumber": "01",
"phone": "011 393 8600",
"createdAt": "2021-06-11T03:11:17.342Z",
"image": "8cfcbf2bcb5e3b4ea8ade44d3825bb52_image.jpg"
}
]
}
So I only want to update the apple object and change the data, I've tried the following code but doesn't seem to work.
`
var db = client.db("test");
try {
db.collection("ShoppingCentres").updateOne({
"title": req.body.product,
"placeListSave.objectId": req.body.id,
}, {
$set: {
"placeListSave.$.email": req.body.email,
"placeListSave.$.storeNumber": req.body.storeNumber,
"placeListSave.$.phone": req.body.phone,
"placeListSave.name": req.body.name,
},
});
res.json("client");
} catch (e) {
console.log("verify", e);
}
});`
arrayFilters seems suitable here:
db.collection.update({
"title": "Products",
"placeListSave.objectId": "0qokn33p773",
},
{
$set: {
"placeListSave.$[x].email": "test#some.email",
"placeListSave.$[x].storeNumber": "test",
"placeListSave.$[x].phone": "test",
"placeListSave.$[x].name": "test"
}
},
{
arrayFilters: [
{
"x.objectId": "0qokn33p773"
}
]
})
explained:
Add array filter called "x" with the objectId for the element that you need to update and use this filter in the $set stage to update the necessary elements.
Hint: To speed up the update you will need to add index on title field or compound index on title+placeListSave.objectId
playground

How to aggregate a MongoDB query to remove the usage of a for loop?

I am new to MongoDB and am working with it on NodeJS code.
As you can see the below code, I am running a for loop through my books collection to figure out the latest version of the query_book.
I know that this isn't efficient, and want to understand how can an aggregation function be written for it in MongoDB.
Current code:
let result= {};
_.forEach(books, function(query_book)
{
if(!result[query_book.book_id])
{
result[query_book.book_id] = query_book
}
else if(result[query_book.book_id].book_version <
query_book.book_version)
{
result[query_book.book_id] = query_book
}
Data Object for books:
[
{
"book_id": "ab12nld”,
"book_version": "0”,
"author": “Sam”,
“name”: “Sample Book”,
“comments”: “Done”
},
{
"book_id": "ab12nld”,
"book_version": "1",
"author": "Martin",
"name": "Sample Book",
“comments”: “In Progress”
},
{
"book_id": "ab12nld”,
"book_version": "2",
"author": "Roy",
"name": "Sample Book",
“comments”: “To-Do”
}
]
[
{
"book_id": "bcj123n”,
"book_version": "0”,
"author": “Don”,
“name”: “Another Book”,
“comments”: “Done”
},
{
"book_id": "bcj123n”,
"book_version": "1",
"author": "Ray",
"name": "Another Book",
“comments”: “In Progress”
},
{
"book_id": "bcj123n”,
"book_version": "2",
"author": "Max",
"name": "Another Book",
“comments”: “To-Do”
}
]
In this case, I want to fetch the object having the maximum value of book_version for my input book_id which is ab12nld:
{
"book_id": "ab12nld”,
"book_version": "2",
"author": "Roy",
"name": "Sample Book",
“comments”: “To-Do”
}
If using Node.js Mongo driver (replace [bookId] with your input)
db.collection('books')
.findOne({ book_id: [bookId] }, { sort: [['book_version', -1]] })
Or, if using Mongoose,
Book.findOne({ book_id: [bookId] }).sort({ book_version: -1 })
db.books.aggregate([{ "$sort": { "book_version": -1 } },{"$limit":1}])
I understood that you want to retrieve a document having highest value of a field.
Here, the document having the highest value in the version field. The simplest way of doing this is to sort in reverse order and get the first document.
You can also use the aggregate method.
Try the following snippet. I think it will help.
db.books.find().sort({"book_version":-1}).limit(1);

How to filter embedded array in mongo document with morphia

Given my Profile data looks like below, I want to find the profile for combination of userName and productId
and only return the profile with the respective contract for this product.
{
"firstName": "John",
"lastName": "Doe",
"userName": "john.doe#gmail.com",
"language": "NL",
"timeZone": "Europe/Amsterdam",
"contracts": [
{
"contractId": "DEMO1-CONTRACT",
"productId": "ticket-api",
"startDate": ISODate('2016-06-29T09:06:42.391Z'),
"roles": [
{
"name": "Manager",
"permissions": [
{
"activity": "ticket",
"permission": "createTicket"
},
{
"activity": "ticket",
"permission": "updateTicket"
},
{
"activity": "ticket",
"permission": "closeTicket"
}
]
}
]
},
{
"contractId": "DEMO2-CONTRACT",
"productId": "comment-api",
"startDate": ISODate('2016-06-29T10:27:45.899Z'),
"roles": [
{
"name": "Manager",
"permissions": [
{
"activity": "comment",
"permission": "createComment"
},
{
"activity": "comment",
"permission": "updateComment"
},
{
"activity": "comment",
"permission": "deleteComment"
}
]
}
]
}
]
}
I managed to find the solution how to do this from the command line. But I don't seem to find a way how to accomplish this with Morphia (latest version).
db.Profile.aggregate([
{ $match: {"userName": "john.doe#gmail.com"}},
{ $project: {
contracts: {$filter: {
input: '$contracts',
as: 'contract',
cond: {$eq: ['$$contract.productId', "ticket-api"]}
}}
}}
])
This is what I have so far. Any help is most appreciated
Query<Profile> matchQuery = getDatastore().createQuery(Profile.class).field(Profile._userName).equal(userName);
getDatastore()
.createAggregation(Profile.class)
.match(matchQuery)
.project(Projection.expression(??))
Note... meanwhile I found another solution which does not use an aggregation pipeline.
public Optional<Profile> findByUserNameAndContractQuery(String userName, String productId) {
DBObject contractQuery = BasicDBObjectBuilder.start(Contract._productId, productId).get();
Query<Profile> query =
getDatastore()
.createQuery(Profile.class)
.field(Profile._userName).equal(userName)
.filter(Profile._contracts + " elem", contractQuery)
.retrievedFields(true, Profile._contracts + ".$");
return Optional.ofNullable(query.get());
}
I finally found the best way (under assumption I only want to return max. 1 element from array) to filter embedded array.
db.Profile.aggregate([
{ $match: {"userName": "john.doe#gmail.com"}},
{ $unwind: "$contracts"},
{ $match: {"contracts.productId": "comment-api"}}
])
To match according to your first design you could try the projection settings with morphia aggregation pipeline.
Query<Profile> matchQuery = getDatastore().createQuery(Profile.class).field(Profile._userName).equal(userName);
getDatastore()
.createAggregation(Profile.class)
.match(matchQuery)
.project(Projection.expression("$filter", new BasicDBObject()
.append("input", "$contracts")
.append("as", "contract")
.append("cond", new BasicDBObject()
.append("$eq", Arrays.asList('$$contract.productId', "ticket-api")));
Also see the example written by the morphia crew around line 88 at https://github.com/mongodb/morphia/blob/master/morphia/src/test/java/org/mongodb/morphia/aggregation/AggregationTest.java.

How to insert array of document in mongodb using node.js?

I want to insert array of document to mongodb using node.js but while inserting it's only inserting first data only.
[{
"userid": "5664",
"name": "Zero 2679",
"number": "1234562679",
"status": "contact",
"currentUserid": "Abcd"
},
{
"userid": "5665",
"name": "Zero 3649",
"number": "1234563649",
"status": "contact",
"currentUserid": "Xyz"
}]
Sample code
collection.insert([{"userid": userid,"name": name,"number": number,"status": status,"currentUserid": currentUserid}], function(err, docs) {
if (err) {
res.json({error : "database error"});
}else {
collection.find({currentUserid:currentUserid}).toArray(function(err, users) {
res.send(users);
});
}});
But it still inserting first value only can you please tell me how to insert all these documents.
Please kindly go through my post and suggest me some solution.
In your sample code you are adding only 1 user.
db.collection('myCollection').insert([doc1, doc2]); inserts two documents using bulk write.
See documentation here: https://docs.mongodb.org/manual/reference/method/db.collection.insert/
From your sample, you can do:
var data = [{
"userid": "5664",
"name": "Zero 2679",
"number": "1234562679",
"status": "contact",
"currentUserid": "Abcd"
},
{
"userid": "5665",
"name": "Zero 3649",
"number": "1234563649",
"status": "contact",
"currentUserid": "Xyz"
}];
db.collection('myCollection').insert(data)
.then(function() {
return db.collection('myCollection').find({number: {$in: ["1234563649", "1234562679"]}});
})
.then(function(res) {
console.log(res);
});

Retrieve elements from MongoDB

I've been looking at some StackOverflow cases such as this case, but I cannot find an example with a document structure close to this one.
Below is an example of one document within my collection artistTags. All documents follow the same structure.
{
"_id": ObjectId("5500aaeaa7ef65c7460fa3d9"),
"toptags": {
"tag": [
{
"count": "100",
"name": "Hip-Hop"
},
{
"count": "97",
"name": "french rap"
},
...{
"count": "0",
"name": "seen live"
}
],
"#attr": {
"artist": "113"
}
}
}
1) How can I find() this document using the "artist" value (here "113")?
2) How can I retrieve all "artist" values having a specific "name" value (say "french rap") ?
Referring to chridam answer here above:
db.collection.find({"toptags.#attr.artist": "113"})

Resources