I have a MongoDB document with an array called forms, inside the array each item is a dictionary, there are a couple of documents in this format, each document has an email field for user identification, and each dictionary has an identifier called title.
My question is how do I check if a specific dictionary is inside the array using the title parameter and retrieve the index, and how do I ensure that I will find the item in the current user document?
Thanks
Ok after some research I found a way:
def already_exists(self, new_form, email):
raw_idx = list(self.users_data_collection.aggregate(
[
{'$match': {'email': email}},
{'$project': {
'index': {'$indexOfArray':['$forms.title',new_form['title']]}
}
}
]
)
)
return raw_idx[0]['index']
I filtered it with the email param to find the correct document and the raw_idx return list of dict which contains the _id field and index field, and then i\I returned the index only.
I hope I have helped someone in need.
Related
I have a mongoose object which contains an array of ObjectIds, being used for population from another table. I want to be able to dedupe these. eg I have
[ '61e34f3293d9361bbb5883c7' ,'61e34f3293d9361bbb5883c7', '61e34f3293d9361bbb5883c7' ]
When i print and iterate through these they look like strings.
But they also have an _id property, so I think they're somehow "populated" or at least contain references to the child table.
What's the best way to do this? I tried:
const uniqueTokens = _.uniqBy(tokens, '_id') which doesn't seem to work as _id is some kind of Object.
converting to a string will allow me to dedupe:
const tokens = this.tokens || []
let newTokens: string[] = []
for (let t of tokens) {
const text = t.toString()
// clog.info('t', t, t._id, typeof t._id)
if (!newTokens.includes(text)) {
newTokens.push(text)
}
}
but then these aren't real Objects I can assign back to the original parent object.
// this.tokens = newTokens
await this.save()
I could maybe go through and re-find the objects, but that seems to be digging deeper into the hole!
Seems there must be a better way to handle these type of types...
related searches
How to compare mongoDB ObjectIds & remove duplicates in an array of documents using node.js?
I also tried using lean() on the tokens array to try and convert it back to a simple list of references, in case somehow the 'population' could be undone to help.
I'm down to creating a unique signature field for the referenced items and de-duping based on that.
I'm doing a dashboard about covid. I want to use a json file but the way data is encapsulated causes me an issue.
As you can see, the "real" name of the country is written inside the "location" field inside the "airport" name. Is there a way I can sort of bypass the "airport" name to access "location" field ? (Maybe like going through all of the "airport" names and search for location inside of them or looking for "location" field directly). Then I will be able to check if the country written in the input matches with one country inside the json file.
There are only these 2 layers ("airport" name & what's inside) in the json file.
About my code, I'm usig react. For now I just fecth the url of the json file to get it.
Thanks in advance !
Just in case someone faces the same issue as me, this helped me find what to do :
Object.keys(data)
Creates an array consisting of all the keys present in the object
Object.values(data)
Creates an array consisting of all the values present in the object
Object.entries(data)
Creates an array consisting of both the keys and values present in the object
In my case, to get location I do this :
for (var i = 0; i < Object.values(data).length; i++) {
if (this.state.country === Object.values(data)[i].location) {
this.setState({
post: Object.values(data)[i]
})
}
}
in my 'rooms' collections, each document has the fields like the following,
{
"createdAt" : 2020.6.4 12:00,
"titleArray" : ["icecream", "summer"]
}
And I want to query to check if a collection contains a document with ["icecream", "summer"] as "titleArray" field, I couldn't find a way to query by an array field itself. In other words, is there a way to passing in an array directly?
I'm having an elastic search index which has the following document sample in it :
{
"height": 2824,
"details": {
'gomathi':{'name':'gomathi','age':10},
'janu':{'name':'janu','age':20}
}
}
The data are pushed into elasticsearch dynamically from user. My goal is to fetch all documents that are containing name as gomathi.
Expected output:
Return documents having the 'gomathi' key in 'details' JSON object.
How to solve this?
Thanks in advance.
I assume details is a nested field in mapping. You could use inner_hits in a nested query for the requirement explained.
Please take a look at inner_hits and nested documentation.
I am trying to make a Meteor app to let users push a value to the database. It works ok, but there a small issue. As soon a certain user has pushed his information, i don't want to let the same user create another entry. Or this must be blocked, or the value the user is pushing must be overwritten for the value he is posting the second time. Now I get multiple entry's of the same user.
Here is my code. Hope you can help me here. Thanks in advance.
Estimations.update(userstory._id, {
$addToSet: {
estimations: [
{name: Meteor.user().username, estimation: this.value}
]
}
});
From the mongo docs
The $addToSet operator adds a value to an array unless the value is
already present, in which case $addToSet does nothing to that array.
Since your array elements are objects the value is the entire object, not just the username key. This means a single user can create multiple name, estimation pairs as long as the estimation value is different.
What you can do is remove any value for the user first, then reinsert:
var username = Meteor.user().username;
Estimations.update({ userstory._id },
{ $pull: { estimations: { name: username }}}); // if it doesn't exist this will no-op
Estimations.update({userstory._id },
{ $push: { estimations: { name: username, estimation: this.value }}});
By way of commentary, you've got a collection called Estimations that contains an array called estimations that contains objects with keys estimation. This might confuse future developers on the project ;) Also if your Estimations collection is 1:1 with UserStorys then perhaps the array could just be a key inside the UserStory document?