MongoDB -Query documents where nested array fields is equal to some value - mongodb

I have a JSON object:
{
"ownershipSheetB": {
"lrUnitShares": [{
"description": "blabla1",
"lrOwners": [{
"lrOwnerId": 35780527,
"name": "somename1",
"address": "someadress1",
"taxNumber": "12345678910"
}
],
"lrUnitShareId": 29181970,
"subSharesAndEntries": [],
"orderNumber": "1"
}, {
"description": "blabla2",
"lrOwners": [{
"lrOwnerId": 35780528,
"name": "somename2",
"address": "someadress2",
"taxNumber": "12345678911"
}
],
"lrUnitShareId": 29181971,
"subSharesAndEntries": [],
"orderNumber": "2"
}
],
"lrEntries": []
}
}
I would like to query all documents that have taxNumber field equal to some string (say "12345678911" from the example above).
I have tried this query:
{"ownershipSheetB.lrUnitShares": { "lrOwners": {"taxNumber": "12345678910"}}}
but it returns no documents.

Solution 1: With dot notation
db.collection.find({
"ownershipSheetB.lrUnitShares.lrOwners.taxNumber": "12345678910"
})
Demo Solution 1 # Mongo Playground
Solution 2: With $elemMatch
db.collection.find({
"ownershipSheetB.lrUnitShares": {
$elemMatch: {
"lrOwners": {
$elemMatch: {
"taxNumber": "12345678910"
}
}
}
}
})
Demo Solution 2 # Mongo Playground

Related

Mongo DB aggregate match not returning value

I have the following mongo db schema and I am trying to build an aggregate query that searches under github_open_issues under the repo key and can return me a match for all the values with repoA as the value. I have tried the following as my query however its not returning any result. Im a bit confused why this is not working as I have another db with a schema similar to this and this type of query works there but here something seems to be different and is not working. I have also put together this interactive example mongoplayground
query
db.collection.aggregate([
{
"$unwind": "$github_open_issues"
},
{
"$match": {
"github_open_issues.repo": {
"$in": [
"repoA"
]
}
}
},
])
schema
[
{
"github_open_issues": {
"0": {
"git_url": "https://github.com/",
"git_assignees": "None",
"git_open_date": "2019-09-26",
"git_id": 253113,
"repo": "repoA",
"git_user": "userA",
"state": "open"
},
"1": {
"git_url": "https://github.com/",
"git_assignees": "None",
"git_open_date": "2019-11-15",
"git_id": 294398,
"repo": "repoB",
"git_user": "userB",
"state": "open"
},
"2": {
"git_url": "https://github.com/",
"git_assignees": "None",
"git_open_date": "2021-04-12",
"git_id": 661208,
"repo": "repoA",
"state": "open"
}
},
"unique_label_seen": {
"568": {
"label_name": "some label",
"times_seen": 12,
"535": {
"label_name": "another label",
"times_seen": 1
}
}
}
}
]
$objectToArray convert github_open_issues object to array in key-value format
$filter to iterate loop of above converted array and filter your search condition
$match to filter github_open_issues not empty
$arrayToObject convert github_open_issues array to object
db.collection.aggregate([
{
$addFields: {
github_open_issues: {
$filter: {
input: { $objectToArray: "$github_open_issues" },
cond: { $in: ["$$this.v.repo", ["repoA"]] }
}
}
}
},
{ $match: { github_open_issues: { $ne: [] } } },
{ $addFields: { github_open_issues: { $arrayToObject: "$github_open_issues" } } }
])
Playground
You query is correct but you data in schema placed wrong inside github_open_issues.repo your objects are place by numbers like {"0": {values... }, "1":{values... }} which cannot get your desired value. You can check the playground now playground

don't allow partially matching document to add to array with $push using updateOne function

check a document whether it is partially matching (2 or more fields) with existing documents in array('claims') with $push / $addToSet using updateOne and shouldn't allow to be pushed to array
structure is as follows:
{
"_id": ObjectId("5f50c93dda654e891c903efb"),
"claims":[
{
"username": "Foo",
"claim_id":"12345",
"claimed_at":"2020-08-31T17:18:52.818737",
},
{
"username": "Bar",
"claim_id":"54321",
"claimed_at":"2020-08-31T17:18:52.818737",
}
]
}
couldn't use $addToSet since other field value like claimed_at is not known,
if it was to match single field only like user_id it was working,
I was missing something here
db.claims.updateOne(
{
"_id": ObjectId("5f50c93dda654e891c903efb"),
"claims":{"$ne": {"username":"Foo"}}
},
{
"$push":
{
"claims":
{
"username": "Foo",
"claim_id":"12345",
"claimed_at":"2020-09-02T17:08:23.514342",
}
}
})
You can try using $elemMatch and $not,
db.claims.updateOne({
"_id": ObjectId("5f50c93dda654e891c903efb"),
claims: {
$not: {
$elemMatch: {
username: "Foo",
claim_id: "12345"
}
}
}
}, {
"$push": {
"claims": {
"username": "Foo",
"claim_id": "12345",
"claimed_at": "2020-09-02T17:08:23.514342",
}
}
})

If condition in MongoDB for Nested JSON to retrieve a particular value

I've nested JSON like this. I want to retrieve the value of "_value" in second level. i,e. "Living Organisms" This is my JSON document.
{
"name": "Biology Book",
"data": {
"toc": {
"_version": "1",
"ge": [
{
"_name": "The Fundamental Unit of Life",
"_id": "5a",
"ge": [
{
"_value": "Living Organisms",
"_id": "5b"
}
]
}
]
}
}
}
This is what I've tried, using the "_id", I want to retrieve it's "_value"
db.products.aggregate([{"$match":{ "data.toc.ge.ge._id": "5b"}}])
This is the closest I could get to the output you mentioned in the comment above. Hope it helps.
db.collection.aggregate([
{
$match: {
"data.toc.ge.ge._id": "5b"
}
},
{
$unwind: "$data.toc.ge"
},
{
$unwind: "$data.toc.ge.ge"
},
{
$group: {
_id: null,
book: {
$push: "$data.toc.ge.ge._value"
}
}
},
{
$project: {
_id: 0,
first: {
$arrayElemAt: [
"$book",
0
]
},
}
}
])
Output:
[
{
"first": "Living Organisms"
}
]
You can check what I tried here
If you are using Mongoid:
(1..6).inject(Model.where('data.toc.ge.ge._id' => '5b').pluck('data.toc.ge.ge._value').first) { |v| v.values.first rescue v.first rescue v }
# => "Living Organisms"
6 is the number of containers to trim from the output (4 hashes and 2 arrays).
If I understand your question correctly, you only care about _value, so it sounds like you might want to use a projection:
db.products.aggregate([{"$match":{ "data.toc.ge.ge._id": "5b"}}, { "$project": {"data.toc.ge.ge._value": 1}}])

MongoDb aggregation project onto collection

I've a problem with a huge MongoDb aggregation pipeline. I've many constraint and I've simplified the problem a lot. Hence, don't discuss the goal for this query.
I've a mongo aggregation that gives something similar to this:
[
{
"content": {
"processes": [
{
"id": "101a",
"title": "delivery"
},
{
"id": "101b",
"title": "feedback"
}
]
}
}
]
To this intermediate result I'm forced to apply a project operation in order to obtain something similar to this:
[
{
"results":
{
"titles": [
{
"id": "101a",
"value": "delivery"
},
{
"id": "101b",
"value": "feedback"
}
]
}
}
]
enter code here
But applying this projections:
"results.titles.id": "$content.processes.id",
"results.titles.value": "$content.processes.title"
I obtain this:
[
{
"results":
{
"titles": {
"id": ["101a", "101b"]
"value": ["delivery", "feedback"]
}
}
}
}
]
Collection are created but not in the proper position.
Is it possible to exploit some operator inside the project operation in order to tell mongo to create an array in a parent position?
Something like this:
"results.titles.$[x].value" : "$content.processes.value"
You can use the dot notation to project entire array:
db.col.aggregate([
{
$project: {
"results.titles": "$content.processes"
}
}
])
and if you need to rename title to value then you have to apply $map operator:
db.col.aggregate([
{
$project: {
"results.titles": {
$map: {
input: "$content.processes",
as: "process",
in: {
id: "$$process.id",
value: "$$process.title"
}
}
}
}
}
])

MongoDB - Updating all matching Nested Documents

I have this MongoDB Document Collection. I would like to update a PropertyContractors Phone number for all documents where "ContractorTelephone": "0865215486".
{
"_id": "4",
"PropertyType": "House",
"PropertyNameNumber": "49",
"PropertyStreet": "Paul Street",
"PropertyTown": "Farmleigh",
"PropertyCity": "Waterford City",
"PropertyCounty": "Co Waterford",
"PropertyBedrooms": "3",
"PropertyDescription": "Central, Cheap",
"PropertyFacilities": [
{
"FacilitiesSmoking": "Yes",
"FacilitiesPets": "Yes",
"FacilitiesBroadBand": "Yes",
"FacilitiesTV": "Yes"
}
],
"PropertyAvailable": "1",
"PropertyContractor": [
{
"ContractorName": "John Murphy",
"ContractorTelephone": "0865215486",
"ContractorType": "Plumber"
}
]
}
Ive Tried
db.Property.update(
{ PropertyContractor.ContractorTelephone: "0865215486" },
{
$set: { PropertyContractor.ContractorTelephone: "0854854215" }
},
{ multi: true }
)
But it just says that the . is wrong Syntax
Thanks in advance.
Use the $ positional operator, it identifies an element in an array to update without explicitly specifying the position of the element in the array:
db.Property.update(
{
"PropertyContractor.ContractorTelephone": "0865215486"
},
{
"$set": {
"PropertyContractor.$.ContractorTelephone": "0854854215"
}
},
{ "multi": true }
);