query to find all the elements in array in mongoose dynamically - node.js

query to find all the elements in the array in mongoose dynamically
below is the object
var res1= {
"category":["travel","cafe"],
"amount":"300"
}
There could be more elements in the category but I want to create the query which automatically finds all the elements in the database just like forEach works

The $in operator should to the trick. $in will look for documents where the provided field matches any of the values in the array. the query would look like this:
Detail.find({
category: { $in: ["travel", "cafe"] },
amount: 300
})
assuming the filters are coming in dynamically on the request, and that req.body.categories is an array of desired categories:
Detail.find({
category: { $in: req.body.categories },
amount: req.body.amount
})

Related

MongoDB update query in subarray

An update in the array of objects inside another array of objects.
mongodb field that I'm working on:
otherFields: values,
tasks: [
{
_id: mongodb.objectID(),
title: string,
items:[{
_id: mongodb.objectID(),
title: string,
completed: boolean //field need to be update.
}]
},
{}...
],
otherFields: value
sample mongodb document
I need to find the document using the task_id and the item_id and update a completed field in item of a task. Using the mongoose findOneAndUpdate method
const path = "tasks.$.items." + item_id + "completed";
collectionName.findOneAndUpdate(
{ _id: req.user._id, "tasks._id": taskID },
{ $set: { [path]: true }});
The above query doesn't work!!!
There is no need to use multiple query conditions, since you'd like to update a specific item that has an unique ID. Therefore you could use something along the lines:
collectionName.findOneAndUpdate(
{ 'tasks.items._id': itemID },
...
);
Keep in mind this structure is far away from optimized as it would basically look through the entire database...
Also now that I think of it, you'd also have issue with the update, as there are two nested arrays within the document. Read more here: How to Update Multiple Array Elements in mongodb

MongoDB: How to perform a second match using the results (an array of ObjectIds) of the previous match in aggregation pipeline

I have a MongoDB collection called users with documents that look like:
{
_id: ObjectId('123'),
username: "abc",
avatar: "avatar/long-unique-random-string.jpg",
connections: [ObjectId('abc'), ObjectId('xyz'), ObjectId('lmn'), ObjectId('efg')]
}
This document belongs to the users collection.
What I want to do:
First, find one document from the users' collection that matches _id -> '123'.
Project the connections field received from step 1, which is an array of ObjectIds of other users within the same collection.
Find all documents of users from the array field projected in step 2.
Project and return an array of only the username and avatar of all those users from step 3.
While I know that I can do this in two separate queries. First using findOne which returns the friends array. Then, using find with the results of findOne to get all the corresponding usernames and avatars.
But, I would like to do this in one single query, using the aggregation pipeline.
What I want to know, is it even possible to do this in one query using aggregation?
If so, what would the query look like?
What, I currently have:
await usersCollection
.aggregate([
{ $match: { _id: new ObjectId(userId) } },
{ $project: { ids: "$connections" } },
{ $match: { _id: { $in: "ids" } } },
{
$project: {
username: "$username",
avatar: { $ifNull: ["$avatar", "$$REMOVE"] },
},
},
])
.toArray()
I know this is wrong because each aggregation stage receives the results from the previous stage. So, the second match cannot query on the entire users' collection, as far as I know.
I'm using MongoDB drivers for nodeJS. And I would like to avoid $lookup for possible solutions.

find a product inside a specific category using mongodb and mongoose

I am new to mongodb. I'm trying to query for a particular product in a specific category (for example if I'm in the books category then I would like to query for a particular book by its name i.e., productName) but I'm unable to do so successfully. Could anybody help me with this. I'm attaching the schema below for reference.
const categorySchema = {
name: String,
description: String,
products: [
{
productName: String,
price: String,
thumbnail: String,
description: String
}
]
};
To search by an object into an array you need to use the dot notation and is very simple.
You need a query similar to this:
db.collection.find({
"_id": 0,
"products.productName": "productName"
})
Note that the find has two conditions.
The first one is to look for in the document you want using its _id (if you want all documents which has 'productName' into the array this condition is not neccesary, but for query a single document it does). This is for query into a specific category document.
The second condition is to get those documents which has the value productName for the key productName into the array products.
Check an example here
Also, if you want to return only the subdocument instead of the entire document, you need this query:
db.collection.find({
"_id": 0
},
{
"products": {
"$elemMatch": {
"productName": "productName"
}
}
})
Example here
Using $elementMatch only the subdocument is returned.
Also, using mongoose the query is the same. Something like this.
var find = await model.find({
"_id": 0,
"products.productName": "productName"
})

Mongo Query to search one or more values are present in an array field of a document

I have a collection like below
{
_id: ObjectId(),
account_number: someID,
account_context: {acnt_id:"1234",acnt_name:"Akhil",address:"Kadapa"},
tags:["tag","TaG","User","tag2","usr"]
},
{
_id: OBjectId(),
account_number: someID,
account_context: {acnt_id:"1234",acnt_name:"Akhil",address:"Kadapa"},
tags:["gat","GaT","Hello","tag2","Usr"]
}
I would like to query based on tags.
If I search for "tag" and "gat" , I should get both the documents
If I search for "Tag" , I should get first document
If I search for "tag" and "Hello", I should get both the documents.
Which means if the search field match for any one of the array element in the document I should get that document.
How can I get that?
you can use $elemMatch with $in for this problem like it:
var searchedArray = ["tag","Hello"]
collection.find({
tags: {$elemMatch: {$in:searchedArray}}
}, (err, result)=>{
})
$elemMatch check all elements of an array with her expression. my expression is $in that check filed with all values is there in searchedArray if equal accept it.

Mongoose find array item in stored array

I have a document that stores an array of ids referencing a different collection:
{
title: 'Title of the document',
categories: [
{ _id: 1 },
{ _id: 2 },
{ _id: 3 },
{ _id: 4 },
]
}
Now I want to be able to find all the documents that have at least one of the categories that I pass into an array:
categories: [1, 3, 4]
I have searched stackoverflow and the MongoDB documentation, but I didn't find how to implement this.
I think the $in operator is what you are looking for. It selects documents where the value of a field equals any value in the specified array. Mongo documentation has a helpful page for it with a section for querying values in an array.
You will also need to use dot notation to query for the _id field of the categories array. The docs also have a page for querying an array of embedded documents, which is what you are doing here (you are querying an array of category documents).
For your case, your query object should probably be something like
{ 'categories._id' : { $in: [1, 3, 4] } }

Resources