In a mongo (2.4.x) collection with documents with this structure:
db.col.insert({ "_id" : { "owner" : "john" }, "value" : 10 });
db.col.insert({ "_id" : { "owner" : "mary" }, "value" : 20 });
I am using mongoose (3.5.4) and trying to run an aggregation pipeline without success. This works fine from the mongo command line client:
> db.col.aggregate({ $match : { "_id.owner": "john" } });
{ "result" : [ { "_id" : { "owner" : "john" }, "value" : 10 } ], "ok" : 1 }
But it does not work as expected when I use mongoose:
Col.aggregate(
{ $match : { "_id.owner": "john" } },
function(err, result) {
console.log("ERR : " + err + " RES : " + JSON.stringify(result));
}
);
ERR : null RES : []
This is the mongoose Schema I am using:
var Col = new Schema({
_id: {
owner: String
},
value: Number
});
I have to say that a simple Col.find({ "_id.owner": "john" }) works as expected.
How could I make it work? I can not modify the structure of my documents.
As I workaround I included a $project before the match, but I am still looking for a cleaner solution:
{
$project: {
"_id": 0,
"owner": "$_id.owner",
"value": 1
}
}
Related
my Test Schema:
var TestSchema = new Schema({
testName: String,
topic: {
topicTitle: String,
topicQuestion: [
{
questionTitle: String,
choice: [
{
name: String
age: Number
}
]
}
]
}
}, { collection: 'test' });
var Test = mongoose.model('test', TestSchema);
I want to update one age ($inc)value which I have the choice id.
I can have test id, topicQuestion id and choice id.
How to write this query in mongoose in NodeJS?
Normally I use the below query to update a value:
Test.findOneAndUpdate({ _id: testId }, { $inc: { ... } }, function (err, response) {
...
});
but it is so difficult to get in array and one more array. Thanks
You can use the $[] positional operator to update nested arrays.
router.put("/tests/:testId/:topicQuestionId/:choiceId", async (req, res) => {
const { testId, topicQuestionId, choiceId } = req.params;
const result = await Test.findByIdAndUpdate(
testId,
{
$inc: {
"topic.topicQuestion.$[i].choice.$[j].age": 1
}
},
{
arrayFilters: [{ "i._id": topicQuestionId }, { "j._id": choiceId }],
new: true
}
);
res.send(result);
});
Let's say we have this existing document:
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2116"),
"testName" : "Test 1",
"topic" : {
"topicTitle" : "Title",
"topicQuestion" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211a"),
"questionTitle" : "Question 1 Title",
"choice" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211c"),
"name" : "A",
"age" : 1
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211b"),
"name" : "B",
"age" : 2
}
]
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2117"),
"questionTitle" : "Question 2 Title",
"choice" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2119"),
"name" : "C",
"age" : 3
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2118"),
"name" : "D",
"age" : 4
}
]
}
]
},
"__v" : 0
}
If we want to increment age value of a given choice, we send a PUT request using endpoint like this http://.../tests/5e53e7d9bf65ac4f5cbf2116/5e53e7d9bf65ac4f5cbf211a/5e53e7d9bf65ac4f5cbf211b where
"testId": "5e53e7d9bf65ac4f5cbf2116"
"topicQuestionId": "5e53e7d9bf65ac4f5cbf211a"
"choiceId": "5e53e7d9bf65ac4f5cbf211b"
You need to inform what choice you want and, on the update section, you need change the way you do increment.
Example:
Test.findOneAndUpdate({ _id: testId, topicQuestion.choice._id: choiceId}, { 'topicQuestion.$.choice': {$inc: { age: <numberToIncrement> }}}, {new: true}, function (err, response) {
...
});
my query is returning me an empty array when I try to text search in mongodb I already created an index into my database.
For example:
I have 2 data type of String declared in my model status and mac_address both of them already included in the text index. When I search for a mac_address it gives me the correct data but when I tried to search for the status it returns an empty array.
--Model--
const PhoneSchema = new mongoose.Schema({
status: {
type: String,
default: "DOWN"
},
mac_address: {
type: String,
unique: true
},
});
--Index--
db.phones.createIndex({
status: "text",
mac_address: "text"
});
--Route--
router.get('/search/:searchForData',
async function (req, res) {
try {
const searchPhone = await Phone.find({
$text: {
$search: req.params.searchForData
}
}, {
score: {
$meta: "textScore"
}
}).sort({
score: {
$meta: "textScore"
}
})
res.status(200).json(searchPhone);
} catch (err) {
return res.status(404).json({
error: err.message
});
}
});
db.phones.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "pingphony.phones"
},
{
"v" : 2,
"unique" : true,
"key" : {
"ip" : 1
},
"name" : "ip_1",
"ns" : "pingphony.phones",
"background" : true
},
{
"v" : 2,
"unique" : true,
"key" : {
"mac" : 1
},
"name" : "mac_1",
"ns" : "pingphony.phones",
"background" : true
},
{
"v" : 2,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "$**_text",
"ns" : "pingphony.phones",
"weights" : {
"$**" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
}
]
I expect the output of /phone/search/DOWN to be the data consisting of DOWN status but the actual output I get is []
Try making your query directly from mongo console:
db.phones.find({ $text: { $search: "DOWN" }})
Try using aggregation pipeline:
const searchPhone = await Phone.aggregate(
[
{ $match: { $text: { $search: "DOWN" } } },
{ $sort: { score: { $meta: "textScore" } } },
]
);
If you tried everything and it just didn't go well try using regexp:
const searchQuery = req.params.searchForData.replace(/[.*+?^${}()|[]\]/g, '\$&'); // escape regexp symbols
const searchPhone = await Phone.find({ status: new RegExp(${searchQuery}, 'i') });
I have a dataset like this:
{
"_id" : ObjectId("5a7bee68996b551034015a15"),
"sequenceid" : 1,
"fruit" : [
{
"name" : "#APPLE",
"value" : 2
},
{
"name" : "#BANANA",
"value" : 1
},
{
"name" : "#ORANGE",
"value" : 5
}
}
want to update only Apple value i.e from 2 to 25. Expected result will be:
{
"_id" : ObjectId("5a7bee68996b551034015a15"),
"sequenceid" : 1,
"fruit" : [
{
"name" : "#APPLE",
"value" : 25
},
{
"name" : "#BANANA",
"value" : 1
},
{
"name" : "#ORANGE",
"value" : 5
}
}
I tried the code but this will replace all entry and do only one entry. My code is
db.Collection.update({'sequenceid': 1}, {$set: {'fruit' : {'name': '#APPLE', 'value': parseFloat(25)}}}, function(error, result){
if(error){
console.log('error');
} else {
console.log('success');
}
});
It can produce the result:
{
"_id" : ObjectId("5a7bee68996b551034015a15"),
"sequenceid" : 1,
"fruit" : [
{
"name" : "#APPLE",
"value" : 25
}
}//Delete all my rest entry
How I can Do this. I am a newbie on MongoDB
This will update only the first occurrence of record.For reference MongoDB - Update objects in a document's array (nested updating)
db.collection.update({ _id: ObjectId("5a7bf5586262dc7b9f3a8422") ,"fruit.name" : "#APPLE"},
{ $set:
{
"fruit.$.value" : 25
}
})
If you are writing JavaScript query then you can update like this
db.collection.find({'sequenceid': 1}).forEach(function(x){
x.fruit.forEach(function(y){
if(y.name=="#APPLE")
{
y.value = 25
}
})
db.collection.update({_id:x._id},x)
})
db.Collection.update({
_id: ObjectId("5a7bee68996b551034015a15"),
"fruit": {
$elemMatch: {
"name": "#APPLE"
}
}
}, {
$set: {
"fruit.$.value": 25
}
})
In above update operation $elemMatch operator is used to search a value in an array and in $set stage positional operator $ is used to update value of specific key belonging to an array element
I'm trying to remove an entry from an array which nested in another array as you can see below:
{
"_id" : ObjectId("548f5ca9fa9dc1000016a725"),
"entries" : [
{
"_id" : ObjectId("548f5cc8fa9dc1000016a726"),
"content" : [
{
"order" : ObjectId("5489fa9127f1310000bea2ed"),
"order_id" : "305429245",
"item_id" : "305429245-1"
},
{
"order" : ObjectId("5489fa9127f1310000bea2ce"),
"order_id" : "330052901",
"item_id" : "330052901-1"
}
],
"stop_number" : 1
},
{
"stop_number" : 2,
"expected_arrival" : ISODate("2014-12-15T17:11:11.000Z"),
"expected_departure" : ISODate("2014-12-15T19:03:17.000Z"),
"_id" : ObjectId("548fb2826e52c20000bd2299"),
"content" : []
}
]
}
And i'm trying to remove the entry that have '305429245-1', so i used:
Q.npost(Manifests, 'findOneAndUpdate', [
{ '_id': id },
{
'$pull': {
'entries.content': { item_id: line_item_id }
}
}
])
where 'id' is the ObjectID (548f5ca9fa9dc1000016a725) and line_item_id = 305429245-1, however, this doesn't work. Can anyone let me know what am i doing wrong?
Try to use find and Update functions separately instead of findOneAndUpdate
Model.find({'_id: id'},function(err,callback){...})
{
//handle callback
}
Model.update({'_id: id'}, {$pull: {'entries.content': item_id: line_item_id}}, function(err,callback){..} )
{
//do some logic or handle callback
}
here Model which i mentioned,should be the model you are using.
Consider the following document in the collection named 'CityAssociation'
{
"_id" : "MY_ID",
"ThisCityID" : "001",
"CityIDs" : [{
"CityID" : "001",
"CityName" : "Bangalore"
}, {
"CityID" : "002",
"CityName" : "Mysore"
}],
"CityUserDetails": {
"User" : "ABCD"
}
}
Now I have User value i.e. in above case I have value ABCD and want to find it with only city where the first level's field ThisCityID matches to the embedded array documnet's field CityID. Finally I need to project as follows (for the above case):
{
'UserName': 'ABCD',
'HomeTown':'Bangalore'
}
In Node.js + MongoDB native drive, I wrote a aggregation query as follows which is not working as expected.
collection.aggregate([
{ $match: { 'CityUserDetails.User': 'ABCD', 'CityIDs': { $elemMatch: { CityID: ThisCityID}}} },
{ $unwind: "$CityIDs" },
{ $group: {
_id: '$_id',
CityUserDetails: { $first: "$CityUserDetails" },
CityIDs: { $first: "$CityIDs" }
}
},
{ $project: {
_id: 0,
"UserName": "$CityUserDetails.User",
"HomeTown": "$CityIDs.CityName"
}
}
], function (err, doc) {
if (err) return console.error(err);
console.dir(doc);
}
);
Can anyone tell me how this can be done with query.
Note: On MongoDB schema we don't have control to change it.
You can use the $eq operator to check if the first level's field ThisCityID matches embedded array document's field CityID.
db.city.aggregate([
{ $match : { "CityUserDetails.User" : "ABCD" }},
{ $unwind : "$CityIDs" },
{ $project : {
matches : { $eq: ["$CityIDs.CityID","$ThisCityID"]},
UserName : "$CityUserDetails.User",
HomeTown : "$CityIDs.CityName"
}},
{ $match : { matches : true }},
{ $project : {
_id : 0,
UserName : 1,
HomeTown : 1
}},
])
And the result is:
{
"result" : [
{
"UserName" : "ABCD",
"HomeTown" : "Bangalore"
}
],
"ok" : 1
}