MongoDB Check if a Collection contains a Key - mongodb

I am using the MongoDB Async Driver to create a little Program were i have to save a User-Profile in the Database.
So i have a Database looking like this
`{
"_id" : ObjectId("5a1743f086060f1bbc319cdb"),
"id" : "aUser1",
"SomeArray" : {
"Name" : "SomeName"
}
}
{
"_id" : ObjectId("5a1743f186060f1bbc319cdc"),
"id" : "aUser2",
"SomeArray" : {
"Name" : "SomeName"
}
}
{
"_id" : ObjectId("5a1743f286060f1bbc319cdd"),
"id" : "aUser3",
"SomeArray" : {
"Name" : "SomeName"
}
}`
And now i try to figure out if the User 1 already has created a Profile.
Whith the old driver i would know how but with the , for me new, Async-Driver it sems a little bit tricky, do i have to make an Callback for this ?

Related

Add field to every document with existing data (move fields data to new field)

I have almost no experience in SQL or noSQL.
I need to update every document so that my fields "Log*" are under the new field "Log"
I found some help from this StackOverflow, but I am still wondering how to move the data.
Thank you very much
Original document
// collection: Services
{
"_id" : ObjectId("5ccb4f99f4953d4894acbe79"),
"Name" : "WebAPI",
"LogPath" : "Product\\APIService\\",
"LogTypeList" : [
{
"Name" : "ApiComCounter",
"FileName" : "ApiComCounter.log"
},
{
"Name" : "ApiService",
"FileName" : "ApiService.log"
}
]
}
Final Document
// collection: Services
{
"_id" : ObjectId("5ccb6fa2ae8f8a5d7037a5dd"),
"Name" : "InvoicingService",
"Log" : {
"LogPath" : "Product\\APIService\\",
"LogTypeList" : [
{
"Name" : "ApiComCounter",
"FileName" : "ApiComCounter.log"
},
{
"Name" : "ApiService",
"FileName" : "ApiService.log"
}
]
}
}
This requires MongoDB 4.2 or higher:
db.<collection>.updateMany({}, [
{$set: {"Log.LogPath": "$LogPath", "Log.LogTypeList": "$LogTypeList"}},
{$unset: ["LogPath", "LogTypeList"]}
])

Make nested queries in MongoDB 3.0.7

I have sub-events belonging to events belonging to an user, and I know the user's username - how do I get a list of the sub-events?
Is this going in the right direction? Or is it completely off?
db.subevents.find({_id: {$in:
db.events.find({_id: {$in:
db.users.find({"username":"userx"},{_id:1})}},{_id:1})}})
Edit: Here is a sample of the data structure:
/* Event */
{
"_id" : "XjhAqqNBkezKY3mdN",
"name" : "My event",
"userId" : "FiKsAAAgBb7cNoPH7"
}
/* Subevent */
{
"_id" : "WkYAqBXNpJryp7rum",
"name" : "The subevent",
"eventId" : "hQXNzX3jbWppbAYFH"
}
/* User */
{
"_id" : "RTHh5srhLMQp625zF",
"username" : "userx"
}
Following profesor79's advice to use three different calls, I put together this solution to get all the sub-events belonging to the user:
var userIds = db.users.find({"username":"userx"}).map(function(user) {
return user._id;
});
var eventIds= db.events.find({userId: {$in:userIds}}).map(function(event) {
return event._id;
});
db.subevents.find({eventId:{$in:eventIds}});
The only way is to make 3 ddifrent calls in mongo 3.0.7
GetUSerData
GetEventData
GetSubEventData
As you have relational schema here - this should be easy.
You could improve schema and remove subEvent collection by embedding subEvents documents into one events document
EDIT
/* Event */
{
"_id" : "XjhAqqNBkezKY3mdN",
"name" : "My event",
"userId" : "FiKsAAAgBb7cNoPH7"
"subewents" : [{
"_id" : "WkYAqBXNpJryp7rum",
"name" : "The subevent",
"eventId" : "hQXNzX3jbWppbAYFH"
}, {
"_id" : "WkYAqBXNpJryp7rum2",
"name" : "The subevent2",
"eventId" : "hQXNzX3jbWppbAYFH"
}, {
"_id" : "WkYAqBXNpJryp7rum",
"name" : "The subevent",
"eventId" : "hQXNzX3jbWppbAYFH"
}
]
}
/* User */
{
"_id" : "RTHh5srhLMQp625zF",
"username" : "userx"
}

MongoDB .Net driver 2.0 Builders Filter (field to array comparison)

I need to get all usernames from "followingList.username" and compare with
posts' usernames, if there any match need to add that one to an array.
Person Model
{
"_id" : ObjectId("554f20f5c90d3c7ed42303e1"),
"username" : "fatihyildizhan",
"followingList" : [
{
"_id" : ObjectId("55505b6ca515860cbcf7901d"),
"username" : "gumusluk",
"avatar" : "avatar.png"
},
{
"_id" : ObjectId("58505b6ca515860cbcf7901d"),
"username" : "yalikavak",
"avatar" : "avatar.png"
},
{
"_id" : ObjectId("58305b6ca515860cbcf7901d"),
"username" : "gumbet",
"avatar" : "avatar.png"
}
]
}
Post Model
{
"_id" : ObjectId("554f2df2a388R4b425b89833"),
"username" : "yalikavak",
"category" : "Summer",
"text" : "blue voyage with yacht"
},
{
"_id" : ObjectId("554f2df2a388P4b425b89833"),
"username" : "yalikavak",
"category" : "Winter",
"text" : "is coming ..."
},
{
"_id" : ObjectId("554f2df2a388K4b425b89833"),
"username" : "gumbet",
"category" : "Fall",
"text" : "there are many trees"
}
I try to get result code block as below but couldn't figure it out.
var filter = Builders<Post>.Filter.AnyEq("username", usernameList);
var result = collection.Find(filter).ToListAsync().Result;
Can you help me with this?
Thanks.
The logic is flipped, what you need is an $in query if I understand your use case correctly:
var filter = Builders<Post>.Filter.In("username", usernameList);
var result = collection.Find(filter).ToListAsync().Result;
In your case, username is a simple field and you want to match against a list of candidates. AnyEq is used to check that, from an embedded list of complex objects, at least one matches a criterion. That still translates to a simple query in MongoDB, but requires to 'reach into' the object which needs a more complicated syntax.

MongoDb - Query for specific subdocument

I have a set of mongodb documents with the following structure:
{
"_id" : NUUID("58fbb893-dfe9-4f08-a761-5629d889647d"),
"Identifiers" : {
"IdentificationLevel" : 2,
"Identifier" : "extranet\\test#test.com"
},
"Personal" : {
"FirstName" : "Test",
"Surname" : "Test"
},
"Tags" : {
"Entries" : {
"ContactLists" : {
"Values" : {
"0" : {
"Value" : "{292D8695-4936-4865-A413-800960626E6D}",
"DateTime" : ISODate("2015-04-30T09:14:45.549Z")
}
}
}
}
}
}
How can I make a query with the mongo shell which finds all documents with a specific "Value" (e.g.{292D8695-4936-4865-A413-800960626E6D} in the Tag.Entries.ContactLists.Values path?
The structure is unfortunately locked by Sitecore, so it is not an options to use another structure.
As your sample collection structure show Values is object, it contains only one Value. Also you must check for Value as it contains extra paranthesis. If you want to get Value from given structure try following query :
db.collection.find({
"Tags.Entries.ContactLists.Values.0.Value": "{292D8695-4936-4865-A413-800960626E6D}"
})

Reassign MongoDB _id in shell

I'm trying to use the MongoDB to reassign IDs. However, it is not setting IDs equal to the value I assign, but rather it is creating a new ObjectId. How do I assign my own ID?
> db.pGitHub.find();
{ "_id" : ObjectId("516f202da1faf201daa15635"),
"url" : { "raw" : "https://github.com/Quatlus",
"domain" : "github.com", "canonical" : "https://github.com/quatlus" } }
{ "_id" : ObjectId("516f202da1faf201daa15636"),
"url" : { "raw" : "https://github.com/Quasii",
"domain" : "github.com", "canonical" : "https://github.com/quasii" } }
> db.pGitHub.find().forEach(function(myProfile) {
var oldId = myProfile._id;
myProfile._id = 'exampleid';
db.pGitHub.save(myProfile);
db.pGitHub.remove({_id: oldId});
});
> db.pGitHub.find();
{ "_id" : ObjectId("516f204da1faf201daa15637"),
"url" : { "raw" : "https://github.com/Quatlus",
"domain" : "github.com", "canonical" : "https://github.com/quatlus" } }
{ "_id" : ObjectId("516f204da1faf201daa15638"),
"url" : { "raw" : "https://github.com/Quasii",
"domain" : "github.com", "canonical" : "https://github.com/quasii" } }
I'm using Mongo 2.4.2
Ben, your statements are correct. It's just mongo shell 2.4.2 behaves somehow different than others (server is not affected). You can use mongo shell binary from 2.4.1 for your purpose.
You can only set object IDs before they've been created. After the fact, they cannot be changed. What you're probably doing is creating new objects when you change the IDs like that.
There's more information in the MongoDB docs