Search for multiple documents in mongodb - mongodb

In mongodb, is there a way I can search for multiple items at once? For example, I have a Products collection. I want to return an array of objects products where product_code = 1000, 2000. 3000.
My semi-pseudocode query would be something like:
Products.find({product_code: [1000, 2000, 3000]});
The desired output would be something like:
[
{
"_id":"1",
"product_code":"1000",
"price":"300"
},
{
"_id":"2",
"product_code":"2000",
"price":"500"
},
{
"_id":"3",
"product_code":"3000",
"price":"400"
}
]
I couldn't find anything relating to this in the documentation...

You can use the $in operator to find documents where a field contains any value in the array:
Products.find({product_code: {$in: ['1000', '2000', '3000']}});

Related

MongoDB : Match with element in an array

I am working on a collection called Publications. Each publication has an array of objectives which are ids. I have also a custom array of objectives hand written. Now, I want to select all the publications that contains at least one element of the custom objectives array in their objectives. How can I do that ?
I've been trying to make this works with '$setIntersection' then '$count' and verify that the count is greater than 0 but I don't know how to implement this.
Example :
publication_1: {
'_id': ObjectId("sdfsdf46543")
'objectives': [ObjectId("1654351456341"), ObjectId("123456789")]
}
publication_2: {
'_id': ObjectId("sdfs216546543")
'objectives': [ObjectId("1654351456341"), ObjectId("46531132")]
}
custom_array = [ObjectId("123456789"), ObjectId("2416315463")]
The mongo query should return publication_1.
You can do like the following:
db.publications.find({
"objectives": {
"$in": [
ObjectId("123456789"),
ObjectId("2416315463")
]
}
})
Notice: "123456789" is not a valid ObjectId so the query itself may not work. Here is the working example
Mongodb playground link: https://mongoplayground.net/p/MbZK99Pd5YR
objectives is an array of objects, I guess you can just query that field directly:
let custom_array = [ObjectId("123456789"), ObjectId("2416315463")];
// You can search the array with $in property.
let result = await Model.find({ objectives: {$in : custom_array} })

In MongoDB, how do I update by matching an element within an array of an Embedded query?

Say you have an document saved like this:
{
_id: "1",
thingy: {
moreStuff: [
{
_id:"a",
moreComplicated: [
{
_id:"a1",
info: "test"
},
... // More similar elements
]
},
... // More similar elements
]
}
}
Suppose you already have a way to get the query of the document:
db.getCollection("thingies").find({"_id": 1});
Now you're looking for a way to update the "info" section inside the "a1" object nested within all those other objects and arrays. The only catch to this is that "moreStuff" and "moreComplicated" arrays are being updated constantly, so aiming by array location (like thingy.morestuff.0.moreComplicated.0.info) won't work. The only way to do it is by looking up the unique mongoID of each object.
How would you query the arrays by matching an element to value instead of an index? Bonus points if you can have a "find" query return a similar object.

Retrieve array of field's values from MongoDB collection

I have an abccollection collection whose documents look like:
{
id:123
focusPoint:89652.33
}
I want to retrieve all focusPoint values so that output looks like:
[89652.33, 89999.223, 99666.45, ...]
If you want to get a list without duplicates:
db.abccollection.distinct("focusPoint")
Otherwise, keeping duplicates:
db.abccollection.find({}, { _id: 0, focusPoint: 1 }).map((doc) => doc.focusPoint)
With that you will retrieve all the documents in the abccollection collection and project just the focusPoint field. The raw output of that query (before the map) will be an array of documents with a single field:
[{ focusPoint: 89652.33 }, { focusPoint: 89999.223 }, ...]
If you don't want MongoDB to do the .map in MongoDB, you can also do it in your application.

how to keep all field also do a $elemMatch projection in mongodb

Below is the document:
{
name:"james",
files:[
{name:"file1.txt", content:"..."},
{name:"file2.txt", content:"..."},
{name:"file3.txt", content:"..."}
],
status:4
}
Want to make a query and return:
all root fields include files
files only contain file2.txt info, coze content is very big, only interested in files2.txt
I know using $elemMatch in find query, as below:
db.collection.find(
{'files':{$elemMatch:{name:'file2.txt'}} },
{name:1, status:1, 'files.$':1 }
)
Is there any way to avoid list all the fields in projection and get all the key?
Requirement: ask for all field but not to list the key (don't list name:1, status:1)
Is this what you asking for namely, return all the fields, but for the files field return only "files2.txt" value ?
db.collection.find({ 'files':{$elemMatch:{name:'file2.txt'}} }, { 'files.$':1, name:1, status:1 } )

remove documents with array field's size less than 3 in mongoDB

i have a mongoDB collection named col that has documents that look like this
{
{
intField:123,
strField:'hi',
arrField:[1,2,3]
},
{
intField:12,
strField:'hello',
arrField:[1,2,3,4]
},
{
intField:125,
strField:'hell',
arrField:[1]
}
}
Now i want to remove documents from collection col in which size of the array field is less than 2.
So i wrote a query that looks like this
db.col.remove({'arrField':{"$size":{"$lt":2}}})
Now this query doesnt do anything. i checked with db.col.find() and it returns all the documents. Whats wrong with this query?
With MongoDB 2.2+ you can use numeric indexes in condition object keys to do this:
db.col.remove({'arrField.2': {$exists: 0}})
This will remove any document that doesn't have at least 3 elements in arrField.
From the documentation for $size:
You cannot use $size to find a range of sizes (for example: arrays with more than 1 element).
The docs recommend maintaining a separate size field (so in this case, arrFieldSize) with the count of the items in the array if you want to try this sort of thing.
Note that for some queries, it may be feasible to just list all the counts you want in or excluded using (n)or conditions.
In your example, the following query will give all documents with less than 2 array entries:
db.col.find({
"$or": [
{ "arrField": {"$exists" => false} },
{ "arrField": {"$size" => 1} },
{ "arrField": {"$size" => 0} }
]
})
The following should work
db.col.remove({$where: "this.arrField.length < 2"})