Why can't I insert my data into my MongoDB database? - mongodb

I have exported one of my collections from MongoDB and it looks like the following:
[
{
"_class": "test.Tag",
"title": "My Title",
"_id": {
"$oid": "637a2bc4a9c297b306dd0be9"
}
}
]
Now, I want to add another item to this collection.
I have created a json file exactly in the same format.
However, when I use the following command:
db.tag.insertMany([{"_class": "test.Tag", "title": "New Title","_id": {"$oid": "637a4171833047f9e046f3c9"}}])
I get the error:
MongoBulkWriteError: _id fields may not contain '$'-prefixed fields: $oid is not valid for storage.
I found a couple of similar questions on stackoverflow, e.g. this one, but they didn't help me.
How should I insert something in my database?
When I use MongoDB Compass, there is no problem. It works. But when I try it on my real database on the server, it doesn't work.
If it helps, I am using Mongo version 6.0.1.
Your help would be appreciated.

In the legacy mongo shell there is no helper for extended json format , but in mongosh you can use EJSON to deserialize the extended json and insert it as follow:
> db.test4.insertMany([EJSON.deserialize( {"_id": { "$oid": "637aa8243d58f36141e59c8d"} } )])
{
acknowledged: true,
insertedIds: { '0': new ObjectId("637aa8243d58f36141e59c8d") }
}
>
( The legacy mongo shell was deprecated in MongoDB 5.0 and removed in MongoDB 6.0 )

Related

Comments on queries through MongoDB .Net driver?

Reading up on MongoDB performance troubleshooting I see that MongoDB supports appending comments on queries. We thought we might add our correlationid to queries so we can correlate which features result in slow queries and/or check whether when we discover slowness in a feature if we can spot some slowness in mongodb.
How can we add comments to queries and/or commands through the .net driver?
How can we add comments to queries and/or commands through the .net driver?
You can utilise FindOptions.Comment to set a comment on a query or a command. For example:
var collection = database.GetCollection<MyObject>("collectionName");
var filter = Builders<MyObject>.Filter.Eq("Name", "Foo");
FindOptions myFindOptions = new FindOptions();
myFindOptions.Comment = "THIS IS FEATURE XYZ";
var cursor = collection.Find<MyObject>(filter, myFindOptions).ToList();
Once you set the database profiler i.e. via db.setProfilingLevel(), you can then query the (database).system.profile collection to find it. For example:
db.system.profile.find({
ns:"dbName.collectionName",
"command.comment":"THIS IS FEATURE XYZ"
});
// Example result:
{
"op": "query",
"ns": "dbName.collectionName",
"command": {
"find": "collectionName",
"filter": {
"Name": "Foo"
},
"comment": "THIS IS FROM FEATURE XYZ",
"$db": "dbName",
"lsid": {
"id": UUID("6b722166-f50b-409c-85f0-2711633baff2"))
}
},
....
}
The above .NET/C# code snippet is written using MongoDB .NET/C# driver v2.9.3.

How do I auto insert a timestamp, into my document when a document is created / edited?

I'm just getting started with mongoDB, and coming from a MySQL environment I'm having trouble figuring out how have my documents automatically have fields such as UPDATED, CREATED, DELETED
So when I create an entry like this:
{
"email": "some#test.com",
"name": "bob"
}
I would like it to automatically become this:
{
"email": "some#test.com",
"name": "bob",
"CREATED": 1567120458,
"UPDATED": 1567120458,
"DELETED": null
}
I have found https://docs.mongodb.com/manual/reference/operator/update/currentDate/ this resource which talks about a way of inserting dates, but I am not sure how to use this, or where to place this.
{ $currentDate: { <field1>: <typeSpecification1>, ... } }
I don't know what this piece of code means or where to use it.
I've installed Stuido 3T to help me manage the database, but I don't see any option to use this piece of code.
Construct your query use Date:
db.example.insert({"date":new Date(Date.now())})

CosmoDb with Robomongo cant see document id's?

Can anyone tell me why when I use DataExplorer for CosmoDb DB I get the following:
{
"id": "d502b51a-e70a-40f1-9285-3861880b8d90",
"Version": 1,
...
}
But when I use Robomongo I get:
{
"Version" : 1,
...
}
minus the id?
Thanks
I tried to repro your scenario but it all worked correctly.
The Mongo document in Portal Data Explorer:
The Mongo document in Robo 3T:
They both have the id property.
Are you applying Projections on Robomongo / Robo 3T?
At this moment cosmodb works separately SQL API and Mongo API, each one has different implementation, SQL API use JSON and Mongo use BSON, you need to be clear this while you are creating the document.
If you create the document with a BSON-based tool like Robo3t for example, you are going to get something like this:
{
"_id": {
"$oid": "5be0d98b9cdcce3c6ce0f6b8"
},
"name": "Name",
"id": "5be0d98b9cdcce3c6ce0f6b8",
...
}
Instead, if you create your document with JSON-based like Data Explorer, you are going to get this:
{
"name": "Name",
"id": "6c5c05b4-dfce-32a5-0779-e30821e6c510",
...
}
As you can see, BSON-based needs that _id and inside $oid be implemented to works right, while JSON-based only id is required. So, you need to add the properties while you save the document (see below) or open it with the right tool, as Matias Quaranta recommend, use Azure Storage Explorer or even Data Explorer to get both protocols properly.
Also, if you use a system to create the document and you want to use BSON format, You need to add the $oid, for example in core net is something like this:
public bool TryGetMemberSerializationInfo(string memberName, out BsonSerializationInfo serializationInfo)
{
switch (memberName)
{
case "Id":
serializationInfo = new BsonSerializationInfo("_id", new ObjectIdSerializer(), typeof(ObjectId));
return true;
case "Name":
serializationInfo = new BsonSerializationInfo("name", new StringSerializer(), typeof(string));
return true;
default:
serializationInfo = null;
return false;
}
}

how to query JSON in mongodb

I have following JSON. I want to store it in MongoDB as Json and query it. How can I do it?
JSON
{
"id": 4,
"user": {
"firstname":"Finn",
"lastname":"Balor",
"email":["fb#wwe.com","fb1#wwe.com"],
"password":"whateverHisTaglineIs",
"address":{
"street":"64 victoria street",
"country":"UK"
}
}
}
I am storing this as the following document
> db.users.insert({id: 4,user: {firstname:"Finn",lastname:"Balor",email:["fb#wwe.com","fb1#wwe.com"],password:"whateverHisTaglineIs",address:{street:"64 victoria street", country:"UK"}}})
how can I query this record using country as selector?
You need to query like below, go through MongoDB documentation and learn MongoDB from MongoDB University.
db.users.find({"user.address.country": "UK"})

How to Query MongoDB, only using the value of inner elements and it's path

I am new to MongoDB. And now i got a puzzle:
say i've got a query workable in mongo console
{
"_id": {
"$oid": "50a5e1cd703d7e9c65326bf9"
},
"people":{
"name":"arthur",
"tele": "001-837475"
"address":{
"country":"us",
"state" : "CA",
"city" : "LA"
}
}
}
I've got pretty many record like this. & I want to query for all people who come from CA.
The query below works well in mongo shell
db.test.find({"people.address.state":"CA"})
But I must do the query in Java.
PS: I don't want to use other opensource packages. just the mongodb-java-driver would be delightful.
Thanks.
There should not be any problem, you can use the query in the exact same way:
DBObject query = new BasicDBObject("people.address.state", "CA");
test.find(query);