Fillter array when publishing a mongdb collection - mongodb

I'm trying to return a specific collection, however, I want to filter an array within the collection. I'm not sure if this is possible. In the example below I'm trying to return the collection with _id: 7ARk3dc2JA8g5pamA and filter out the array object for "candidateUserId": "2". I'm doing this in a Meteorjs application.
Eg: `Collection'
{
"_id": "7ARk3dc2JA8g5pamA",
"jobTitle": "Developer",
"candidateApplication": [
{
"candidateUserId": "1",
"applied": true
},
{
"candidateUserId": "2",
"applied": false
}
]
}
Path: Publish command
return Jobs.find({ _id: 7ARk3dc2JA8g5pamA }, {
$filter: {
input: candidateApplication,
cond: { candidateUserId: { $eq: 1 } }
}
});

Jobs.find({ _id: 7ARk3dc2JA8g5pamA }, { candidateApplication: { $elemMatch: { candidateUserId: 2 } } }
This should return the document with only the _id and the candidateUserId array, but that array will now only contain the object that you want.
{ "_id" : 7ARk3dc2JA8g5pamA, "candidateApplication" : [ { "candidateUserId": 2, "applied": false } ] }
You can then get to the data with candidateApplication[0].candidateUserId and candidateApplication[0].applied
As mentioned in the comments above, if there are more instances of that same candidateUserId, only the first will be returned.

Related

MongoDB - Update the value of one field with the value of another nested field

I am trying to run a MongoDB query to update the value of one field with the value of another nested field. I have the following document:
{
"name": "name",
"address": "address",
"times": 10,
"snapshots": [
{
"dayTotal": 2,
"dayHit": 2,
"dayIndex": 2
},
{
"dayTotal": 3,
"dayHit": 3,
"dayIndex": 3
}
]
}
I am trying like this:
db.netGraphMetadataDTO.updateMany(
{ },
[{ $set: { times: "$snapshots.$[elem].dayTotal" } }],
{
arrayFilters: [{"elem.dayIndex":{"$eq": 2}}],
upsert: false,
multi: true
}
);
but got an error:
arrayFilters may not be specified for pipeline-syle updates
You can't use arrayFilters with aggregation pipeline for update query at the same time.
Instead, what you need to do:
Get the dayTotal field from the result 2.
Take the first matched document from the result 3.
Filter the document from snapshots array.
db.netGraphMetadataDTO.updateMany({},
[
{
$set: {
times: {
$getField: {
field: "dayTotal",
input: {
$first: {
$filter: {
input: "$snapshots",
cond: {
$eq: [
"$$this.dayIndex",
2
]
}
}
}
}
}
}
}
}
],
{
upsert: false,
multi: true
})
Demo # Mongo Playground

MongoDb 4.x Query with projection without empty entries using find

We are now using mongo-db to store data from tests. I am using Mongo-Shell
The document is structured like this:
{
static1:"abc",
static2:"xyz",
static3:"asd", [...],
nested:[
{
data1: "d1",
data2: "d2",
},
{
data1: "dx",
data4: "d4",
data5: "d5",
data6: "d6",
},
{
data1: "ds",
data8:"data8"
}, [...]
]
}
So the static-data is always in the same structure, but for every measurement the object can look different. It could be voltage with upper, lower and actual value. Or just comparison of a target value and an actual value. Highly dynamic.
Same data1-name represent same attributes.
Now e.g. I want to display only some static data and one (or several) attributes of a nested document.
I am using this query:
find({}, {_id:0, data1:1, "nested.data8":1}).pretty()
As expected, only the static-data1 is displayed, but the dynamic measurements has lots of empty objects in the shell-output
Example-Output:
{
"static1" : "123",
"nested" : [
{ },
{ },
{ }, [...] ,
{ "data8" : "OK" }
] }
The desired output would be:
{
"static1" : "123",
"nested" : [
{ "data8" : "d8" }
]
}
I also tried this query on the mongo shell:
aggregate( { $addFields: {"static":"$static1", "data8":"$nested.data8"} }, { $project:{"static1":1, "nested.data8":1} } ).pretty()
But the result is the same.
I hope there is a ways to get rid of the empty documents in the output.
Thanks
You can try $filter operator to filter result of nested array by checking condition not equal to empty object {}
db.collection.aggregate([
{
$project: {
_id: 0,
data1: 1,
"nested.data8": 1
}
},
{
$set: {
nested: {
$filter: {
input: "$nested",
cond: { $ne: ["$$this", {}] }
}
}
}
}
])
Playground

How to query MongoDB for complex data

I have a table structured as follows:
db.l2vpn_fdb_database.findOne()
{
_id: ObjectId("5f5257f11324c04122714445"),
hostname: "spine01-drt-red",
l2vpn_fdb_database: {
MAC: [
{
IfIndex: "1631",
MacAddr: "00-00-0C-07-AC-01",
SrvID: "1",
VsiName: "EVPN",
},
{
IfIndex: "0",
MacAddr: "00-00-0C-07-AC-02",
SrvID: "0",
VsiName: "EVPN",
},
{
IfIndex: "1631",
MacAddr: "00-00-0C-07-AC-0A",
SrvID: "1",
VsiName: "EVPN",
},
],
},
}
I'd like to search for "MacAddr" object, could you help me figure out based on above? So essentially I'd like to be able to parse database for a MacAddress assuming it's there and be able to get "IfIndex" for further processing.
Thank you.
You can use $filter to get matched objects
db.collection.aggregate([
{
$project: {
l2vpn_fdb_database: {
$filter: {
input: "$l2vpn_fdb_database.MAC",
cond: {
$eq: [
"$$this.IfIndex",
"1631"
]
}
}
}
}
}
])
Working Mongo playground
for Hostname with macAddr try like this,
db.collection.aggregate([
{
$project: {
l2vpn_fdb_database: {
$filter: {
input: "$l2vpn_fdb_database.MAC",
cond: {
$eq: [
"$$this.IfIndex",
"1631"
]
}
}
},
hostname:{
$eq:['$hostname','spine01-drt-red']
}
}
}
])
This query could help you.
b.l2vpn_fdb_database.findOne({
"l2vpn_fdb_database.MAC.MacAddr": "00-00-0C-07-AC-01",
},
{
"l2vpn_fdb_database.MAC.$": 1
})
The result is the same document just with 1 element in the array
Result:
{
"_id": ObjectId("5f5257f11324c04122714445"),
"l2vpn_fdb_database": {
"MAC": [
{
"IfIndex": "1631",
"MacAddr": "00-00-0C-07-AC-01",
"SrvID": "1",
"VsiName": "EVPN"
}
]
}
}

How to avoid adding duplicate objects to an array in MongoDB

this is my schema:
new Schema({
code: { type: String },
toy_array: [
{
date:{
type:Date(),
default: new Date()
}
toy:{ type:String }
]
}
this is my db:
{
"code": "Toystore A",
"toy_array": [
{
_id:"xxxxx", // automatic
"toy": "buzz"
},
{
_id:"xxxxx", // automatic
"toy": "pope"
}
]
},
{
"code": "Toystore B",
"toy_array": [
{
_id:"xxxxx", // automatic
"toy": "jessie"
}
]
}
I am trying to update an object. In this case I want to update the document with code: 'ToystoreA' and add an array of subdocuments to the array named toy_array if the toys does not exists in the array.
for example if I try to do this:
db.mydb.findOneAndUpdate({
code: 'ToystoreA,
/*toy_array: {
$not: {
$elemMatch: {
toy: [{"toy":'woddy'},{"toy":"buzz"}],
},
},
},*/
},
{
$addToSet: {
toy_array: {
$each: [{"toy":'woddy'},{"toy":"buzz"}],
},
},
},
{
new: false,
}
})
they are added and is what I want to avoid.
how can I do it?
[
{
"code": "Toystore A",
"toy_array": [
{
"toy": "buzz"
},
{
"toy": "pope"
}
]
},
{
"code": "Toystore B",
"toy_array": [
{
"toy": "jessie"
}
]
}
]
In this example [{"toy":'woddy'},{"toy":"buzz"}] it should only be added 'woddy' because 'buzz' is already in the array.
Note:when I insert a new toy an insertion date is also inserted, in addition to an _id (it is normal for me).
As you're using $addToSet on an object it's failing for your use case for a reason :
Let's say if your document look like this :
{
_id: 123, // automatically generated
"toy": "buzz"
},
{
_id: 456, // automatically generated
"toy": "pope"
}
and input is :
[{_id: 789, "toy":'woddy'},{_id: 098, "toy":"buzz"}]
Here while comparing two objects {_id: 098, "toy":"buzz"} & {_id: 123, "toy":"buzz"} - $addToSet consider these are different and you can't use $addToSet on a field (toy) in an object. So try below query on MongoDB version >= 4.2.
Query :
db.collection.updateOne({"_id" : "Toystore A"},[{
$addFields: {
toy_array: {
$reduce: {
input: inputArrayOfObjects,
initialValue: "$toy_array", // taking existing `toy_array` as initial value
in: {
$cond: [
{ $in: [ "$$this.toy", "$toy_array.toy" ] }, // check if each new toy exists in existing arrays of toys
"$$value", // If yes, just return accumulator array
{ $concatArrays: [ [ "$$this" ], "$$value" ] } // If No, push new toy object into accumulator
]
}
}
}
}
}])
Test : aggregation pipeline test url : mongoplayground
Ref : $reduce
Note :
You don't need to mention { new: false } as .findOneAndUpdate() return old doc by default, if you need new one then you've to do { new: true }. Also if anyone can get rid of _id's from schema of array objects then you can just use $addToSet as OP was doing earlier (Assume if _id is only unique field), check this stop-mongoose-from-creating-id-property-for-sub-document-array-items.

MongoDB aggregate - filter by subdocument

I have a mongodb collection with structure like that:
[
{
name: "name1",
instances: [{value:1, score:2}, {value:2, score:5}, {value:2.5, score:9}]
},
{
name: "name2",
instances: [{value:6, score:3}, {value:1, score:6}, {value:3.7, score:5.2}]
}
]
When I want to get all the data from a document, I use aggregate because I want each instance returned as a separate document:
db.myCollection.aggregate([{$match:{name:"name1"}}, {$unwind:"$instances"}, {$project:{name:1, value:"$instances.value", score:"$instances.score"}}])
And everything works like I want it to.
Now for my question: I want to filter the returned data by score or by value. For example, I want an array of all the subdocuments of name1 which have a value greater or equal to 2.
I tried to add to the $match object 'instances.value':{$gte:2}, but it didn't filter anything, and I still get all 3 documents for this query.
Any ideas?
After unwinding instances then again used $match as below
db.collectionName.aggregate({
"$match": {
"name": "name1"
}
}, {
"$unwind": "$instances"
}, {
"$match": {
"instances.value": {
"$gte": 2
}
}
}, {
$project: {
name: 1,
value: "$instances.value",
score: "$instances.score"
}
})
Or if you tried $match after project then used as below
db.collectionName.aggregate([{
$match: {
name: "name1"
}
}, {
$unwind: "$instances"
}, {
$project: {
name: 1,
value: "$instances.value",
score: "$instances.score"
}
}, {
"$match": {
"value": {
"$gte": 2
}
}
}])