How to retrieve data from a complex data structure in MongoDB? - javascript

Data:
Is there any way to access all of these "lineText" fields from the collection in MongoDB through a single query?

Try this
db.collectionName.aggregate([
{ $unwind: "$text" },
{ $unwind: "$text.paragraphs" },
{
$group: {
_id: null,
result: {
$push: {
$arrayElemAt: ["$text.paragraphs.lineText", 0]
}
}
}
},
{
$project: {
result: {
$reduce: {
input: "$result",
initialValue: "",
in: { "$concat": ["$$value", "$$this"] }
}
}
}
}
]);

Related

how to catch mongo change streams when one key in object gets updated

I am using the mongo change stream to update some of my data in the cache. This is the Documentation i am following.
I want to know when one of the keys in my object gets updated.
Schema :- attributes: { position: { type: Number } },
How will I come to know when the position will get updated?
This is how my updateDescription object looks like after updation
updateDescription = {
updatedFields: { 'attributes.position': 1, randomKey: '1234'},
removedFields: []
}
Tried this and its not working
Collection.watch(
[
{
$match: {
$and: [
{ operationType: { $in: ['update'] } },
{
$or: [
{ 'updateDescription.updatedFields[attributes.position]': { $exists: true } },
],
},
],
},
},
],
{ fullDocument: 'updateLookup' },
);
I was able to fix it like this,
const streamUpdates = <CollectionName>.watch(
[
{
$project:
{
'updateDescription.updatedFields': { $objectToArray: '$updateDescription.updatedFields' },
fullDocument: 1,
operationType: 1,
},
},
{
$match: {
$and: [
{ operationType: 'update' },
{
'updateDescription.updatedFields.k': {
$in: [
'attributes.position',
],
},
},
],
},
},
],
{ fullDocument: 'updateLookup' },
);
and then do something with the stream
streamUpdates.on('change', async (next) => {
//your logic
});
Read more here MongoDB

How to get grouped data as well as all data using mongodb?

Using the following code, I do get totalAccount and totalBalance. But, no other field/data is showing up. How can I also get all data from my collection that matches my query (brcode)?
const test = await db.collection('alldeposit').aggregate([
{
$match: {
brcode: brcode
}
},
{
$group: {
_id: null,
totalAccount: {
$sum: 1
},
totalBalance: {
$sum: "$acbal"
}
}
}
]).toArray()
You have to specify which fields you want to see in the $group stage
For example:
await db.collection('alldeposit').aggregate([
{
$match: {
brcode: brcode
}
},
{
$group: {
_id : null,
name : { $first: '$name' },
age : { $first: '$age' },
sex : { $first: '$sex' },
province : { $first: '$province' },
city : { $first: '$city' },
area : { $first: '$area' },
address : { $first: '$address' },
totalAccount: {
$sum: 1
},
totalBalance: {
$sum: "$acbal"
}
}
}]);
Edit:
Regarding our chat in the comments, unfortunately I don't know a way to do the operation you asked in a single aggregation.
But with two steps, you can do it:
First step:
db.collection.aggregate([
{
$match: {
brcode: brcode
}
},
{
"$group": {
"_id": null,
totalAccount: {
$sum: 1
},
totalBalance: {
$sum: "$acbal"
}
}
}
])
And second step:
db.collection.update(
{ brcode: brcode }
,{$set : {
"totalAccount": totalAccount,
"totalBalance": totalBalance
}}
)

Use mongoDB $lookup to find documents in another collection not present inside an array

I'm using the aggregate framework to query a collection and create an array of active players (up until the last $lookup) after which I'm trying to use $lookup and $pipeline to select all the players from another collection (users) that are not present inside the activeUsers array.
Is there any way of doing this with my current setup?
Game.aggregate[{
$match: {
date: {
$gte: ISODate('2021-04-10T00:00:00.355Z')
},
gameStatus: 'played'
}
}, {
$unwind: {
path: '$players',
preserveNullAndEmptyArrays: false
}
}, {
$group: {
_id: '$players'
}
}, {
$group: {
_id: null,
activeUsers: {
$push: '$_id'
}
}
}, {
$project: {
activeUsers: true,
_id: false
}
}, {
$lookup: {
from: 'users',
'let': {
active: '$activeUsers'
},
pipeline: [{
$match: {
deactivated: false,
// The rest of the query works fine but here I would like to
// select only the elements that *aren't* inside
// the array (instead of the ones that *are* inside)
// but if I use '$nin' here mongoDB throws
// an 'unrecognized' error
$expr: {
$in: [
'$_id',
'$$active'
]
}
}
},
{
$project: {
_id: 1
}
}
],
as: 'users'
}
}]
Thanks
For negative condition use $not before $in operator,
{ $expr: { $not: { $in: ['$_id', '$$active'] } } }

How to delete an element in a sub sub document mongoosejs

how to delete the "extras" with "id_extra = 8523" of the "book" "id_book = 8522" of that particular user?, I currently use mongoosejs but I didn't succeed, I tried many stuffs, but whatever I tried was working just till the first level of nested doc.
{
"_id":{
"$oid":"5e32fce08919b53ad66cf694"
},
"user_id":{
"$numberInt":"258787"
},
"username":"daaaa",
"firstname":"davide",
"api_key":"7b031c21edf1237c554867622ad1154f",
"books":[
{
"_id":{
"$oid":"5e356323a0ef6319ebb60162"
},
"id_book":{
"$numberInt":"8522"
},
"blob_annotation":null,
"extra_id":{
"$numberInt":"995176"
},
"extras":[
{
"_id":{
"$oid":"5e356324a0ef6319ebb60163"
},
"id_extra":{
"$numberInt":"8523"
},
"type":"gallery_audio",
"label":"Inverno a Boscodirovo"
},
{
"_id":{
"$oid":"5e356324a0ef6319ebb60164"
},
"id_extra":{
"$numberInt":"8524"
},
"type":"gallery_audio",
"label":"Storia di Primavera"
}
],
"raccolte":[
]
}
],
}
Try using elemMatch in conjunction with $:
db.books.update(
{
books: {
$elemMatch: {
"id_book": 8522,
"extras.id_extra": 8523
}
},
user_id: 258787
},
{
$pull: {
"books.$.extras": {
"id_extra": 8523
}
}
}
)
You may do this trick: Filter "extras" with "id_extra = 8523" of the "book" "id_book = 8522" and save documents again in MongoDB
db.collection.aggregate([
{
$match: {
"books.id_book": 8522
}
},
{
$addFields: {
"books": {
$reduce: {
input: "$books",
initialValue: [],
in: {
$concatArrays: [
"$$value",
[
{
_id: "$$this._id",
id_book: "$$this.id_book",
blob_annotation: "$$this.blob_annotation",
extra_id: "$$this.extra_id",
raccolte: "$$this.raccolte",
extras: {
$filter: {
input: "$$this.extras",
cond: {
$ne: [
"$$this.id_extra",
8523
]
}
}
}
}
]
]
}
}
}
}
}
])
MongoPlayground

Mongodb sort by result of $indexOfCp

Is there a way to sort in MongoDB by $indexOfCp without adding it as field
Currently that what I'm doing
Food.aggregate([
{ $match: { name: { $regex: search } } },
{ $addFields: { score: { $indexOfCP: ['$name', search] } } },
{ $sort: { score: 1 } }
])
How can I do that 👆 without $addFields?

Categories

Resources