How to convert mongodb array of object to array of string [duplicate] - javascript

This question already has answers here:
How to return only value of a field in mongodb
(6 answers)
Closed 3 months ago.
I am using mongodb with mongoose in NodeJs project.
I want to convert my data array of object to array of string like
[
{
id: '6375ce97e8ec382b8dbf8433',
},
{
id: '638de425cbb676123ad204f6',
},
{
id: '638de425cbb676123ad20509',
},
{
id: '6375ce97e8ec382b8dbf8433',
},
{
id: '638dc4cc48b1de03d0d920b7',
},
{
id: '638de425cbb676123ad204f6',
},
{
id: '6375ce97e8ec382b8dbf8433',
},
];
Convert to
['6375ce97e8ec382b8dbf8433',
'638de425cbb676123ad204f6',
'638de425cbb676123ad20509',
'6375ce97e8ec382b8dbf8433',
'638dc4cc48b1de03d0d920b7',
'638de425cbb676123ad204f6',
'6375ce97e8ec382b8dbf8433']
How I convert my data using mongodb not JavaScript method like, map, filter, find etc
I did not convert the data because lack of mongodb knowledge.

You cannot do this directly within mongodb. The reason is that a document must be an object. Eg, you cannot replace the object with a string. Instead, you have 3 options:
1 - Get the output very close, but you just have to locate the array: https://mongoplayground.net/p/furNa_ezJ5l
db.collection.aggregate([
{
$group: {
_id: null,
data: {
$push: "$$ROOT.id"
}
}
}
])
Gives you:
[
{
"_id": null,
"data": [
"6375ce97e8ec382b8dbf8433",
"638de425cbb676123ad204f6",
"638de425cbb676123ad20509",
"6375ce97e8ec382b8dbf8433",
"638dc4cc48b1de03d0d920b7",
"638de425cbb676123ad204f6",
"6375ce97e8ec382b8dbf8433"
]
}
]
Where the data you want will be:
const stringArray = result[0].data
2 - Use JS after your query
db.collection.find({}).toArray().map( function(u) { return u.id } )
3 - Magic distinct values
Assuming that your values of id are always unique and that you don't want to do any further querying or aggregation, you can ask mongo for the unique ones:
db.collection.distinct('id')
Which should give you:
['6375ce97e8ec382b8dbf8433',
'638de425cbb676123ad204f6',
'638de425cbb676123ad20509',
'6375ce97e8ec382b8dbf8433',
'638dc4cc48b1de03d0d920b7',
'638de425cbb676123ad204f6',
'6375ce97e8ec382b8dbf8433']

Related

Filter nested array in object based on specific values of another array [duplicate]

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Closed 7 months ago.
I have an array of Objects, and every object has an array of strings (tags), I need to filter the array of objects based on another array.
data: [
{
"id":"Nerium",
"tags":["CMS Selection", "Experience Design", "Development","UX"],
"featured":0
},
{
"id":"WesternDigital",
"tags":["Digital Strategy", "Analytics", "Example"],
"featured":1
},
{
"id":"Example",
"tags":["Example", "Analytics", "UX"],
"featured": 0,
},
I need to filter the above data based on an Array like this:
activeTags: ['UX', 'Example']
And the objects of Data I filter need to specifically have the values inside activeTags, in this case if for example an Object has 'UX' but it doesn't have 'Example', I don't return it.
Expected output:
data: [{
"id": "Example",
"tags": ["Example", "Analytics", "UX"],
"featured": 0,
}]
Or it should return every Object that has tags that specifically have the values in activeTags
This should work
const data = [
{
id: "Nerium",
tags: ["CMS Selection", "Experience Design", "Development", "UX"],
featured: 0,
},
{
id: "WesternDigital",
tags: ["Digital Strategy", "Analytics", "Example"],
featured: 1,
},
{
id: "Example",
tags: ["Example", "Analytics", "UX"],
featured: 0,
},
];
const activeTags = ["UX", "Example"];
const filtered = data.filter(({ tags }) =>
activeTags.every((tag) => tags.includes(tag))
);
console.log(filtered);
you can use .every to check that the object has all the active tags
I haven't tested, but I think the following should work:
const result = data.filter( record =>
activeTags.every( tag =>
record.tags.includes( tag )
)
);
filter() returns array with only elements that pass its function test. every() returns true only if every element passes its function test. includes() will test if the element is included in the record.tags array.

Update multiple elements of array in mongodb document with appropriate element of javascript array

I have array of objects with following structure:
const myArr = [{
'name':'question1',
'grade':6
},
{
'name':'question2',
'grade':7
}]
Question collection:
{
_id:623749f845844e7d273d801c,
questions:[
{
'name':'question1',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801m
},
{
'name':'question2',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801a
},
{
'name':'question3',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801f
}
]
}
I just want to update all objects in array questions in collection which i have provided in myArr array. So the desired result should be:
{
_id:623749f845844e7d273d801c,
questions:[
{
'name':'question1',
'grade':6,
'someInfo':'blabla',
_id:623749f845844e7d273d801m
},
{
'name':'question2',
'grade':7,
'someInfo':'blabla',
_id:623749f845844e7d273d801a
},
{
'name':'question3',
'grade':10,
'someInfo':'blabla',
_id:623749f845844e7d273d801f
}
]
}
What i've found so far:
I managed to update grade when i specify the question name with positional operator:
await Prijave.updateOne(
{
_id: mongoose.Types.ObjectId(q_id),
'questions.name': 'question1',
},
{
$set: {
'questions.$.grade': '10',
},
}
)
But how to do this for every element in myArr ? I could make forEach loop which iterates through myArrand call updateOne for every element but i dont think it should be done that way because it will make multiple connection to database instead of one.

how to concate all the members id from that mongodb collection?

I have a collection named group on the mongoDb database . The collection includes 2 or more object and each object contains an array named members . what is the best possible and efficient way to concate and get all the members data from the database. what would be the mongoDB query ?
my collection looks like
[
{
id: ObjcetId("15215252"),
groupName: "travellers of Bangladesh",
members: ["1","2","3"]
},
{
id: ObjcetId("32643724362"),
groupName: "People from Bangladesh",
members: ["4","5","6"]
}
]
and i Want just this exact data
members: ["1","2","3","4","5","6"]
Use can use aggregations
$unwind to deconstruct the array
$group to reconstruct the array
Here is the code
db.collection.aggregate([
{ $unwind: "$members" },
{
$group: {
_id: null,
members: { $push: "$members" }
}
}
])
Working Mongo playground

How to access property on JSON with Arrays and Objects [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I have this JSON:
[
{ someTitle: 'NAME OF SomeTitle' },
[
{
id: '7oiqxhRXRqEV0D70G',
photo: 'https://co/image/ab67616d739a3e7d0c38c3af225e4695ce',
jugement: 'GOAl',
Name: 'Some Name.'
}
],
{
token: 'BQAVhYiUweHGTTlIIZHthAKzulZ-DHg'
}
]
This comes from a request I make to my node Server. If I do a console.log(req.body) I get the information above.
So when I try to do console.log(req.body.token) I get undefined.
How can I access the token property then?
The size of the JSON may change , so I can't just access it by index.
Since it is an array of objects, and the element you are looking for is at the 3th position of the array. You need to call it using index = 2 (because index starts with 0).
After that, you can access token property.
const res = [{
someTitle: 'NAME OF SomeTitle'
},
[{
id: '7oiqxhRXRqEV0D70G',
photo: 'https://co/image/ab67616d739a3e7d0c38c3af225e4695ce',
jugement: 'GOAl',
Name: 'Some Name.'
}],
{
token: 'BQAVhYiUweHGTTlIIZHthAKzulZ-DHg'
}
]
console.log(res[2].token)
Check this out
console.log(req.body[2]["token"])
If Array size is not fixed then try this
let req = {
body: [
{ someTitle: "NAME OF SomeTitle" },
[
{
id: "7oiqxhRXRqEV0D70G",
photo: "https://co/image/ab67616d739a3e7d0c38c3af225e4695ce",
jugement: "GOAl",
Name: "Some Name.",
},
],
{
token: "BQAVhYiUweHGTTlIIZHthAKzulZ-DHg",
},
],
};
let data = req.body;
let token = "";
for (let each of data) {
if (each.hasOwnProperty("token")) {
token = each["token"];
break;
}
}
console.log(token)

Using $lookup on an array of objects to join two documents in MongoDB [duplicate]

This question already has answers here:
MongoDB join data inside an array of objects
(2 answers)
Closed 4 years ago.
I have many Shop documents that each contain a field products which is an array of objects where the key is the product ID and the value is the quantity in stock:
{ products: [{"a": 3}, {"b": 27}, {"c": 4}] }
I have a collection Products where each product has a document containing productId, name, etc:
{ productId: "a", "name": "Spanner"}
I would like to pull in/aggregate/join the product information for each of those items. I know how to do it when the field is a single ID, and I have seen this answer which describes how to do it for an array of IDs. But I am having a bit of trouble wrapping my head around what to do with an array of objects containing IDs.
Desired output:
{
products: [
{ {productId: "a", "name": "Spanner"}: 3 }
]
}
(And no, it is not within my control to switch to a relational database.)
I think if you want to using ID for reference, try to avoid place it as object keys, instead make it as object property like { products: [{"productId": $_id, "quantity": 3}]}, that could be a reason for downvote.
But if you cant change it, you can using $objectToArray in aggregation to convert your array.
One more thing, your desire output is unreal because object property in js cant not be an object.
Try it:
db.Shop.aggregate(
// Pipeline
[
// Stage 1
{
$unwind: {
path : "$products"
}
},
// Stage 2
{
$project: {
products: { $objectToArray: "$products" }
}
},
// Stage 3
{
$unwind: {
path : "$products"
}
},
// Stage 4
{
$project: {
productId: "$products.k",
productQuantity: "$products.v"
}
},
// Stage 5
{
$lookup: {
"from" : "products",
"localField" : "productId",
"foreignField" : "productId",
"as" : "products"
}
},
// Stage 6
{
$unwind: {
path : "$products"
}
},
// Stage 7
{
$project: {
productId: "$productId",
productQuantity: "$productQuantity",
productName: "$products.name"
}
},
]);
Good luck

Categories

Resources